1

How to render the content of ng-content in the component and the menu?

I try to do using the answer from this question How to use multiple ng-content in the same component in Angular 2?, But it's not works as expected.

When I open the menu then the buttons are disappear from the component.

How to fix that? I want to have the buttons in the component and in the menu.

stackblitz

usage:

  <container>
    <button mat-raised-button (click)="foo()">foo</button>
    <button mat-raised-button (click)="bar()">bar</button>
  </container>

container:

  <section id="buttons">
    <ng-container *ngTemplateOutlet="contentTpl"></ng-container>
  </section>
  
  <button mat-button [matMenuTriggerFor]="menu">Menu</button>
  <mat-menu #menu="matMenu">
    <ng-container *ngTemplateOutlet="contentTpl"></ng-container> 
  </mat-menu>

  <ng-template #contentTpl><ng-content></ng-content></ng-template>
Cristian18
  • 220
  • 3
  • 12
Jon Sud
  • 10,211
  • 17
  • 76
  • 174

1 Answers1

1

Yes, that is because it only render in one <ng-content>. You can use <ng-template> to solve that.

@Component({
  selector: 'container',
  template: `
    <section id="buttons">
        <ng-container *ngTemplateOutlet="content"></ng-container>
    </section>
  
    <button mat-button [matMenuTriggerFor]="menu">Menu</button>

    <mat-menu #menu="matMenu">
        <ng-container *ngTemplateOutlet="content"></ng-container> 
    </mat-menu>
  `,
})
export class Container {
  @Input() content: TemplateRef<any>;
}

@Component({
  selector: 'menu-overview-example',
  template: `
    <container [content]="content"></container>

    <ng-template #content>
        <button mat-raised-button (click)="foo()">foo</button>
        <button mat-raised-button (click)="bar()">bar</button>
    </ng-template>
  `,
})
export class MenuOverviewExample {}

Or you can place the <ng-template> inside the tags:

<container>
    <ng-template>
        <button mat-raised-button (click)="foo()">foo</button>
        <button mat-raised-button (click)="bar()">bar</button>
    </ng-template>
</container>

And:

@ContentChild(TemplateRef) content: TemplateRef<any>;
Cristian18
  • 220
  • 3
  • 12
  • Is it possible to keep the syntax without ng-template? ` ` or maybe wrap the `button` in component? – Jon Sud Oct 09 '21 at 12:04