就像 JavaScript 的 switch 语句一样。NgSwitch 会根据切换条件显示几个可能的元素中的一个。Angular 只会将选定的元素放入 DOM。
在每个元素(比如 <div>)上,把 [ngSwitch] 绑定到一个返回开关值的表达式(比如 feature)。尽管这个例子中 feature 值是字符串,但此开关值可以是任何类型。
将各个分支元素绑定到 *ngSwitchCase 和 *ngSwitchDefault。
app.component.html
<div [ngSwitch]="currentItem.feature">
<app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item>
<app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item>
<app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item>
<app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item>
<!-- . . . -->
<app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item>
</div>
在父组件中,定义 currentItem 以便可以在 [ngSwitch] 表达式中使用它。
app.component.ts
currentItem!: Item;
在每个子组件中,添加一个输入属性 item,该属性会绑定到父组件的 currentItem。以下两个片段显示了父组件和其中一个子组件。其他子组件与 StoutItemComponent 中的相同。
child.component.ts
export class StoutItemComponent {
@Input() item!: Item;
}
Switch 指令也同样适用于内置 HTML 元素和 Web Component。比如,你可以像下面的例子中一样把 <app-best-item> 分支替换为 <div>
app.component.html
<div *ngSwitchCase="'bright'"> Are you as bright as {{currentItem.name}}?</div>