* ng如果在模板中,否则 [英] *ngIf else if in template

查看:90
本文介绍了* ng如果在模板中,否则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*ngIf语句中如何处理多个案例?我已经习惯了Vue或Angular 1具有ifelse ifelse的功能,但似乎Angular 4仅具有true(if)和false(else )条件.

How would I have multiple cases in an *ngIf statement? I'm used to Vue or Angular 1 with having an if, else if, and else, but it seems like Angular 4 only has a true (if) and false (else) condition.

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

According to the documentation, I can only do:

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

但是我想有多个条件(类似):

But I want to have multiple conditions (something like):

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

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

But I'm ending up having to use ngSwitch, which feels like a hack:

  <ng-container [ngSwitch]="true">
    <div *ngSwitchCase="foo === 1">First</div>
    <div *ngSwitchCase="bar === 2">Second</div>
    <div *ngSwitchDefault>Third</div>
  </ng-container>

或者,似乎我从Angular 1和Vue习以为常的许多语法在Angular 4中均不受支持,那么采用这种条件构造代码的推荐方法是什么?

Alternately, it seems like a lot of the syntaxes I've got used to from Angular 1 and Vue aren't supported in Angular 4, so what would be the recommended way to structure my code with conditions like this?

推荐答案

另一种方法是嵌套条件

<ng-container *ngIf="foo === 1;else second"></ng-container>
<ng-template #second>
    <ng-container *ngIf="foo === 2;else third"></ng-container>
</ng-template>
<ng-template #third></ng-template>

这篇关于* ng如果在模板中,否则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆