2016-09-05 70 views
1

我有IF語句模板:如何在模板中使用ngSwitch?

<li *ngIf="activity.entity_name == 'Project'" [activity-project-item]="activity"></li> 
<li *ngIf="activity.entity_name == 'Tooling'" [activity-tooling-item]="activity"></li> 
<li *ngIf="activity.entity_name != 'Project' && activity.entity_name != 'Tooling'" [activity-item]="activity"></li> 

如何寫這個模板,ngSwitch指令?

例如這個模板具有 「上的嵌入式模板組件」 解析錯誤:

<li [ngSwitch]="activity.entity_name"> 
    <template [ngSwitchCase]="'Project'" [activity-project-item]="activity"></template> 
</li> 

而這個模板有分析錯誤 「無提供NgSwitch」:

<template [ngSwitch]="activity.entity_name"> 
    <li [ngSwitchCase]="'Project'" [activity-project-item]="activity"></li> 
</template> 

回答

1

模板

<li [ngSwitch]="activity.entity_name"> 
    <template [ngSwitchCase]="'Project'">Content here</template> 
    <template [ngSwitchCase]="'Project2'">Other content here</template> 
    <template ngSwitchDefault>Content if nothing matched</template> 
</li> 

還要確保臨時t擁有此組件的模塊導入CommonModule。否則,ngSwitch將不被識別。

@NgModule({ 
    ... 
    imports: [CommonModule...], 
    declarations: [ThisComponent...], 
    ... 
}) 
export default class MyModule {} 
4

一種可能性:

<li [ngSwitch]="activity.entity_name"> 
    <template [ngSwitchCase]="'Project'">Selected Project</template> 
    <template [ngSwitchCase]="'Tooling'">Selected Tooling</template> 
    <template ngSwitchDefault>Or else...</template> 
</li> 

替代語法:

<div [ngSwitch]="activity.entity_name"> 
    <li *ngSwitchCase="'Project'">Selected Project</li> 
    <li *ngSwitchCase="'Tooling'">Selected Tooling</li> 
    <li *ngSwitchDefault>Or else...</li> 
</div> 

看看的official docslive demo