Angular ngIf 在其他方面有多个语句



你如何在else下写ngif和多个语句?我有一种感觉,我正在做一些愚蠢的事情,但很惊讶在这种情况下除了我之外没有找到其他人。*ngIf=col !='actions';否则显示动作;我愿意添加另一个作业这里;

if(condition){
statement1;
statement2;
}else
{statement3;
statement4;
statement5;
}

仅仅因为有人不理解这个问题并不意味着这个问题不清楚。这就是为什么我上次离开SO的原因,停止标记你不理解的问题,让其他理解的人回答或忽略它。

您是否正在寻找then else

<ng-container *ngIf="col !='actions'; then noActions; else showActions;></ng-container>
<ng-template #noActions>
I have no actions
</ng-template>
<ng-template #showActions>
I have some actions
</ng-template>

您甚至可以使用多个扩展它

<ng-container *ngIf="col !='actions'; then noActions; else (col === 'actions' && showActions) || (something === 3 && somethingElse)";></ng-container>
<ng-template #noActions>
I have no actions
</ng-template>
<ng-template #showActions>
I have some actions
</ng-template>
<ng-template #somethingElse>
I have some something else
</ng-template>

谢谢,我确实看过,但不符合我的要求。我没想到我会陷入这么简单的事情,但我在这里。当 if 条件计算结果为 true 或 false 时,我有什么方法可以有多个语句吗?

我想你正在寻找ngSwitch

请参阅 https://angular.io/api/common/NgSwitch

更新:

经过深思熟虑,我希望,我终于能够弄清楚你的要求......

<ng-container *ngIf="col !='actions'; else multilpleActions">
...
</ng-container>
<ng-template #multilpleActions>
<ng-container *ngTemplateOutlet="showAction"></ng-container>
<ng-container *ngTemplateOutlet="anotherAction"></ng-container>
</ng-template>
<ng-template #showAction>
...
</ng-template>
<ng-template #anotherAction>
...
</ng-template>

我真的希望这有所帮助。

更新(编辑后(

让我指出,*ngIf不适用于按顺序工作的代码语句,而是适用于只是文本的 HTML 模板。*ngIf单个元素执行布尔运算,并允许您从 2 个模板中选择要呈现到其中的模板。在任何给定时间,您只能将一个模板呈现为一个元素。所以你所要求的是不可能的。如果需要将多个模板呈现到一个元素,唯一的出路是将它们作为父元素的子元素,并将父元素呈现为元素。

祝您编码愉快!

根据最佳实践,模板上不应有更多逻辑。因为它可能会导致难以跟踪的错误和未经测试的情况。

在组件中移动这些逻辑。并创建多个标志,然后尝试显示/隐藏确切的细分。

在模板中处理此类多个条件的最佳方法是使用 ngSwitch,请查看 Angular 文档 https://angular.io/api/common/NgSwitch

最新更新