ng-content有/无选择器在组件中多次使用时不显示内容

时间:2018-07-19 06:56:56

标签: angular

我有一个布局组件,负责处理如何根据输入变量呈现元素。

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>

和我要显示视图的app.component.html是

<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>

只有具有layout1的视图才能正确呈现,而其他视图则不呈现任何内容。

Stackbitz网址:https://stackblitz.com/edit/angular-wm2bdg

1 个答案:

答案 0 :(得分:1)

  1. 您应为select中的ng-content使用不同的名称
  2. 对于没有ng-content的{​​{1}},您应该删除该属性。

layout.component.html

select

和我要显示视图的app.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>