* ng如果在模板中,否则

编程入门 行业动态 更新时间:2024-10-23 10:29:31
本文介绍了* ng如果在模板中,否则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在*ngIf语句中如何处理多个案例?我已经习惯了Vue或Angular 1具有if,else if和else的功能,但似乎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如果在模板中,否则

本文发布于:2023-10-18 10:51:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!