在组件中使用这些div:
<div ngIf="condition1">
<button (click)="set_condition1_false_and_2_true()">show-template-2</button>
</div>
<div ngIf="condition2>
<button (click)="set_condition2_false_and_3_true()">show-template-3</a>
</div>
<div ngIf="condition3>
<a>Last Template</a>
</div>假设typescript可以正确地处理布尔值,我需要做什么才能创建这个视图?
(观察)使用两个div,我让它工作:
<div *ngIf="condition1; else secondTemplate>
<button (click)="make_condition1_false_and_2_true()">showSecondTemplate
</button>
</div>
<ng-template #secondTemplate>
<a>Second Template Works</a>
</ng-templante> 但是我需要在同一个组件中有三个模板
发布于 2018-02-26 11:02:24
最简单但可能不是最好的方法是简单地检查*ngIf语句中的其他条件是否为真。
省略除ifs之外的所有代码
<div *ngIf="!condition2 && !condition3 && condition1">
<div *ngIf="!condition1 && !condition3 && condition2">
<div *ngIf="!condition1 && !condition2 && condition3> 或者,您可以使用NgSwitch。如果您的所有条件都基于相同的变量,这很容易,但假设它们不是,您可以使用helper函数来实现。
<div [ngSwitch]="getState()">
<div *ngSwichCase="1">
<div *ngSwichCase="2">
<div *ngSwichCase="3">
</div>然后在您的typescript中使用if/ Then /else定义getState函数
getState() {
if (condition1) {
return 1;
} else if (condition2) {
return 2;
} else {
return 3;
}
}在实际的代码中,您可能希望使用一个更有意义的名称,并返回一个具有有意义的名称的枚举值,而不是魔术数字。
https://stackoverflow.com/questions/48979673
复制相似问题