*ngIf else if 在模板中 [英] *ngIf else if in template

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

问题描述

如何在 *ngIf 语句中包含多个 case?我习惯于 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>

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

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