【问题标题】:Nested Condition in *ngIf using ng-container*ngIf 中的嵌套条件使用 ng-container
【发布时间】:2021-07-16 06:08:47
【问题描述】:

我正在处理需要根据某些条件显示行列表的要求。 有一个表格单元格(td),其值应根据某些条件填充。 我希望使用 *ngIf

以角度实现以下目标
if(value1||values2)
{
    if(value3!=null && value4==null)
    {
        //display value 3
    }
    else
    {
     //display value 4
    }
}
else
{
//display default value
}

我想要达到的目标的图示 我使用 *ngIf 尝试过,但出现错误 **Bidings cannot contain assignments **

<ng-container *ngIf="(value1 || value2); else showDefault">
    <ng-container *ngIf="value3!=null && value4==null; else showValue4">
    </ng-container>
    <ng-template #showValue4>
    </ng-template>
</ng-container>
<ng-template #showDefault>
</ng-template>

还有其他方法可以实现吗?

【问题讨论】:

  • 您似乎缺少第一个 *ngIf 周围的引号和第二个之后的结束引号
  • 是的!那是一个拼写错误。我刚刚更新了。

标签: angular if-statement angular-ng-if


【解决方案1】:

虽然您的解决方案看起来不错。另一种方法是使用ngTemplateOutlet 指令。

这样您就可以准备好您的ngTemplates,然后通过模板名称来决定您要使用的内容,如下所示:

<ng-container *ngTemplateOutlet="selected">
  This text is not displayed
</ng-container>

<ng-template #template1>
  <p>This is our template.</p>
</ng-template>

<ng-template #template2>
  <p>This is another template.</p>
</ng-template>

<ng-template #template3>
  <p>This is one more template.</p>
</ng-template>

<button (click)="selected = template1" >1</button>
<button (click)="selected = template2" >2</button>
<button (click)="selected = template3" >3</button>

Here你可以阅读更多。

Here我创建了一个 StackBlitz 来玩。

【讨论】:

  • 谢谢你的例子。但我想实现我在问题中给出的 If else 示例。在您的示例中,我只能关联两个条件。您能否为多种条件提供相同的条件。
  • 当然可以!再看看 StackBlitz:stackblitz.com/edit/angular-ivy-zekhbs?file=src/app/…
  • NgTemplateOutlet 是 Angular 提供的一个非常特殊的功能,我建议您阅读我与您分享的文章,我相信它对您将来会有很大帮助。
  • 我刚刚添加了我想要使用嵌套条件实现的图表。有没有办法做到这一点,如图所示。
  • 如果您了解插座模板的工作原理,您可以自行完成。所有信息都在这里...
【解决方案2】:

试试

<ng-container *ngIf="value3 && !value4; else showValue4">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2022-07-07
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多