1

I have a need to create several md-menus dynamically. Due to the requirement of template reference variables in their syntax this seems not to be an easy task.

eg. If I had an ngFor repeating several cases of a component instance with a template such as the below snippet, I am not able to adjust the # name due to their static nature (unless there is a way?)

<button [mdMenuTriggerFor]="menu">
    <i class="{{icon}}">{{menu_header}}</i>
</button>
<md-menu #menu="mdMenu">
    <button md-menu-item *ngFor="let m of menu_items">{{m}}</button>
</md-menu>

Is there a technique that can be utilized for such a component/template embedded within an ngFor?

monsterAdurm
  • 63
  • 1
  • 7

1 Answers1

1

Try by using dynamic component rendering with ng-container. Example:

@Component({
    selector: 'menu-element-a', 
    template: '<li>My menu element. Add more stuff</li>'
})
class MenuElementA {
}
@Component({
  selector: 'ng-my-menu',
  template: `<ng-container *ngComponentOutlet="MenuElementA "></ng-container>`
})
class NgMyMenu {
  MenuElementA = MenuElementA;
}

I solved this issue myself here: Angular2: Use Pipe to render templates dynamically

I ended up having a constant with some component names (form fields, inputs, etc.) and in my form view I would render the fields dynamically where each field is a component itself.

So you could have something like:

export const MENU_OPTIONS = [
   'ComponentA',
   'ComponentB',
   'ComponentC',
]

Where each one of them is a component.

And then you could use it like this:

<menu>
   <menu-element *ngFor="let field of MENU_OPTIONS">
        <ng-container *ngComponentOutlet="field";
             ngModuleFactory: myComponentsModule;"></ng-container>
   </menu-element>
</menu>

Where myComponentsModule is the module that contains the components within the constant that we declared.

Documentation: https://angular.io/docs/ts/latest/api/common/index/NgComponentOutlet-directive.html

Community
  • 1
  • 1
SrAxi
  • 19,787
  • 11
  • 46
  • 65