2saurabh
2saurabh

Reputation: 1

ng-content with/without selector doesn't shows content when used more than once in a component

I have a layout component that takes care of how elements need to be rendered based on input variable.

layout.component.ts

export class LayoutComponent  {
  @Input() mode: 'layout1' | 'layout2' | 'none' = 'none';
}

layout.component.html

<ng-container [ngSwitch]="mode">

  <ng-container *ngSwitchCase="'layout1'">
    <h1>Layout1</h1>
    <ng-content select="[title]"></ng-content>
    <ng-content select="[content]"></ng-content>
  </ng-container>

  <ng-container *ngSwitchCase="'layout2'">
    <h1>Layout2</h1>
    <ng-content select="[content]"></ng-content>
    <ng-content select="[title]"></ng-content>
  </ng-container>

  <ng-container *ngSwitchCase="'none'">
    <h1>None</h1>
    <ng-content></ng-content>
  </ng-container>

</ng-container>

and my app.component.html to show views is

<my-app-layout [mode]="'layout1'">
  <div title>Title</div>
  <div content>Content</div>
</my-app-layout>

<my-app-layout [mode]="'layout2'">
  <div title>Title</div>
  <div content>Content</div>
</my-app-layout>

<my-app-layout [mode]="'none'">
  <div title>Title</div>
  <div content>Content</div>
</my-app-layout>

Only view with layout1 is rendering properly, for other views no content is rendered.

Stackbitz url: https://stackblitz.com/edit/angular-wm2bdg

Upvotes: 0

Views: 1129

Answers (1)

Emon
Emon

Reputation: 1549

  1. You should use different name for select in ng-content
  2. for the ng-content without select, you should remove the attribute.

layout.component.html

  <ng-container *ngSwitchCase="'layout1'">
    <h1>Layout1</h1>
    <ng-content select="[title]"></ng-content>
    <ng-content select="[content]"></ng-content>
  </ng-container>

  <ng-container *ngSwitchCase="'layout2'">
    <h1>Layout2</h1>
    <ng-content select="[content2]"></ng-content>
    <ng-content select="[title2]"></ng-content>
  </ng-container>

  <ng-container *ngSwitchCase="'none'">
    <h1>None</h1>
    <ng-content></ng-content>
  </ng-container>

and my app.component.html to show views is

<my-app-layout [mode]="'layout1'">
  <div title>Title</div>
  <div content>Content</div>
</my-app-layout>

<my-app-layout [mode]="'layout2'">
  <div title2>Title</div>
  <div content2>Content</div>
</my-app-layout>

<my-app-layout [mode]="'none'">
  <div>Title</div>
  <div>Content</div>
</my-app-layout>

Upvotes: 1

Related Questions