Sergey A
Sergey A

Reputation: 157

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

How to include menu-items into child components
See example:
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>

It works, but not as expected.
I can see that items, and menu working by click, but I'm unable to use keyboard for items access. Also in dropdown.component.ts if I get access to MdMenu component via @ViewChild('navMenu') it shows me 0 items
this.mdMenu.items // 0

Upvotes: 0

Views: 318

Answers (1)

yurzui
yurzui

Reputation: 214017

MdMenu directive uses @ContentChildren to get list of MdMenuItem.

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

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

As ContentChildren works only for the component-owner of template your menu directive will always have 0 items.

Workaround could be as follows

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

See also

Upvotes: 1

Related Questions