Switching menus programmatically if I have multiple menus?

If I have two menu components in my template as shown below

<button md-icon-button [md-menu-trigger-for]="menu">
    <md-icon>more_vert</md-icon>
</button>
<md-menu #menu="mdMenu">
  <button md-menu-item>Refresh</button>
  <button md-menu-item>Settings</button>
  <button md-menu-item>Help</button>
  <button md-menu-item disabled>Sign Out</button>
</md-menu>

<button md-icon-button [md-menu-trigger-for]="menu1">
    <md-icon>more_vert</md-icon>
</button>
<md-menu #menu1="mdMenu">
  <button md-menu-item>Refresh</button>
  <button md-menu-item>Settings</button>
  <button md-menu-item>Help</button>
  <button md-menu-item disabled>Sign Out</button>
</md-menu>

How to programmatically switch the second component of the menu ?. Usually @ViewChild (MdMenuTrigger) we can use the following if I have only one menu component in the template. Is there a way, by specifying the component name in @ViewChild, to find out the nth component of the menu and open the menu programmatically?

+4
source share
1 answer

first you need to bind AfterViewInit to your component

class YourComponent implements AfterViewInit {

then you can do it using @ViewChildren

@ViewChildren(MdMenuTrigger) triggers: QueryList<MdMenuTrigger>; 
// use ViewChildren to get a list of menu element

ngAfterViewInit() {

  // inside ngAfterViewInit lifecycle
  // you get the triggers

  this.triggers.forEach((item)=>{
    item.openMenu();
  });

}
+1
source

Source: https://habr.com/ru/post/1664768/


All Articles