如何将 md-menu 项目嵌入 Material md-menu

How to do transclusion md-menu items into Material md-menu

如何将菜单项包含到子组件中
参见示例:
dropdown.component.html

<div class="dropdown">
    <button md-icon-button
            [mdMenuTriggerFor]="dropMenu">
        <i class="glyphicon glyph-more"></i>
    </button>
</div>
<md-menu #navMenu="dropMenu" [overlapTrigger]="false">
    <ng-content></ng-content> 
    <!-- after rendering I'm able to see all buttons, 
         and interact with them my mouse click.
         But they not accessible with keyboard -->
</md-menu>

header.component.html

<div class="header">
  ...
  <dropdown>
    <button md-menu-item>Button 1</button>
    <button md-menu-item>Button 2</button>
    <button md-menu-item>Button 3</button>
  </dropdown>
  ...
</div>

有效,但不如预期。
我可以通过单击看到这些项目和菜单,但我无法使用键盘访问项目。 同样在 dropdown.component.ts 中,如果我通过 @ViewChild('navMenu') 访问 MdMenu 组件,它会显示 0 项
this.mdMenu.items // 0

MdMenu 指令使用 @ContentChildren 获取 MdMenuItem 的列表。

@ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

ngAfterContentInit() {
  this._keyManager = new FocusKeyManager(this.items).withWrap();
  this._tabSubscription = this._keyManager.tabOut.subscribe(() => this._emitCloseEvent());
}

由于 ContentChildren 仅适用于模板的组件所有者,您的菜单指令将始终具有 0 项。

解决方法如下

dropdown.component.ts

...
export class DropDownComponent {
  @ViewChild(MdMenu) menu: MdMenu;

  @ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

  ngAfterViewInit() {
    this.menu.items = this.items;
    this.menu.ngAfterContentInit();
  }
}

Plunker Example

另见