angular4 html 模板迭代和 ngIf 指令
angular4 html template iteration and ngIf directive
我正在使用 ngFor 结构指令将对象数组绑定到我的 html 模板,如下所示:
<div *ngFor=let g of groupsList">
g 引用的每个组都包含一个 属性 类型。 groupsList 中的元素已经按类型排序。意思是元素0-10中的对象应该是TypeA,11-35中的元素是TypeB,等等。但是总对象数和每种类型的对象数是动态的。
我需要将每个对象的类型与其之前的对象进行比较,并根据这两个值是否不同显示或不显示上面显示的不同 div。
由于 ngFor 指令,模板中发生了 groupsList 迭代。因此,我假设我也必须在模板中而不是在我的组件中进行这种比较。
这样做的正确方法是创建几个 ng 容器并以两种方式绑定到我的组件中名为 priorType 和 currentType 的两个变量吗?
更新了简短的解决方案:
<div *ngFor="let g of groupsList; let i=index">
<div *ngIf="(i==0) || (i>0 && g.type != groupsList[i-1].type)">
这里是示例 html,您可以在其中将一个对象与其之前的对象进行比较,并根据比较显示不同的 div
。
<div *ngFor="let g of groupsList; let i = index">
<div *ngIf="i == 0">
{{ g | json }}
</div>
<div *ngIf="i > 0 ">
{{ g | json }}
<h4 *ngIf="(groupsList[i].type != groupsList[i-1].type)" style="background: green">Type doesn't match with previous</h4>
<h4 *ngIf="(groupsList[i].type == groupsList[i-1].type)" style="background: red">Type matches with previous</h4>
</div>
</div>
希望对您有所帮助!
我正在使用 ngFor 结构指令将对象数组绑定到我的 html 模板,如下所示:
<div *ngFor=let g of groupsList">
g 引用的每个组都包含一个 属性 类型。 groupsList 中的元素已经按类型排序。意思是元素0-10中的对象应该是TypeA,11-35中的元素是TypeB,等等。但是总对象数和每种类型的对象数是动态的。
我需要将每个对象的类型与其之前的对象进行比较,并根据这两个值是否不同显示或不显示上面显示的不同 div。
由于 ngFor 指令,模板中发生了 groupsList 迭代。因此,我假设我也必须在模板中而不是在我的组件中进行这种比较。
这样做的正确方法是创建几个 ng 容器并以两种方式绑定到我的组件中名为 priorType 和 currentType 的两个变量吗?
更新了简短的解决方案:
<div *ngFor="let g of groupsList; let i=index">
<div *ngIf="(i==0) || (i>0 && g.type != groupsList[i-1].type)">
这里是示例 html,您可以在其中将一个对象与其之前的对象进行比较,并根据比较显示不同的 div
。
<div *ngFor="let g of groupsList; let i = index">
<div *ngIf="i == 0">
{{ g | json }}
</div>
<div *ngIf="i > 0 ">
{{ g | json }}
<h4 *ngIf="(groupsList[i].type != groupsList[i-1].type)" style="background: green">Type doesn't match with previous</h4>
<h4 *ngIf="(groupsList[i].type == groupsList[i-1].type)" style="background: red">Type matches with previous</h4>
</div>
</div>
希望对您有所帮助!