相关疑难解决方法(0)

如何使用*ngIf else?

我正在使用Angular,我希望*ngIf else在此示例中使用(自版本4起可用):

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现同样的行为ngIf else

if-statement angular-template angular

559
推荐指数
18
解决办法
60万
查看次数

*ng if if if in template

我如何在*ngIf声明中有多个案例?我习惯于Vue或Angular 1有一个if,else ifelse,但似乎Angular 4只有一个true(if)和false(else)条件.

根据文档,我只能这样做:

  <ng-container *ngIf="foo === 1; then first else second"></ng-container>
  <ng-template #first>First</ng-template>
  <ng-template #second>Second</ng-template>
  <ng-template #third>Third</ng-template>
Run Code Online (Sandbox Code Playgroud)

但我希望有多种条件(类似):

  <ng-container *ngIf="foo === 1; then first; foo === 2; then second else third"></ng-container>
  <ng-template #first>First</ng-template>
  <ng-template #second>Second</ng-template>
  <ng-template #third>Third</ng-template>
Run Code Online (Sandbox Code Playgroud)

但我最终不得不使用ngSwitch,感觉就像一个黑客:

  <ng-container [ngSwitch]="true">
    <div *ngSwitchCase="foo === 1">First</div>
    <div *ngSwitchCase="bar === 2">Second</div>
    <div *ngSwitchDefault>Third</div>
  </ng-container>
Run Code Online (Sandbox Code Playgroud)

或者,似乎很多Angular 1和Vue中习惯使用的语法在Angular 4中都不受支持,那么建议用这样的条件构造代码的方法是什么?

templates angular-ng-if angular

80
推荐指数
7
解决办法
9万
查看次数