如何根据条件angular2使用ngFor渲染不同的项目

how to render different items using ngFor based on a condition angular2

我必须使用 ngFor 动态创建一些 html 组件。需要根据 json.

的值呈现不同的项目,如文本框、select 等

我知道如何在 javascript 中使用 for 循环和 if 条件来做到这一点。但是 angular 2 中的替代项是什么?

例如

for(var i=0;i<data.length;i++){
    if(data.type=="textbox"){
      $('#container').append(//textbox snippet)
    }

    if(data.type=="select"){
      $('#container').append(//select snippet)
    }
}

在 angular 2 中,替代方案是什么?非常感谢任何帮助。

您可以使用 *ngIf 指令。

例如:

<div *ngIf="(data.type == 'textbox')">
<!--textbox snippet here-->
</div>

<input *ngIf="(data.type == 'textbox')" type="text" value="" />

这是关于 *ngIf 指令的 documentation