[英]angular4 html template iteration and ngIf directive
I am binding an array of objects to my html template using the ngFor structural directive like this: 我使用ngFor结构指令将对象数组绑定到我的html模板,如下所示:
<div *ngFor=let g of groupsList">
Each group referenced by g contains a property called type. g引用的每个组都包含一个称为type的属性。 The elements in groupsList are already sorted by type.
groupsList中的元素已经按类型排序。 Meaning objects in elements 0-10 should have TypeA, elements in 11-35 are TypeB, etc. However the number of total objects and objects of each type are dynamic.
表示元素0-10中的对象应具有TypeA,元素11-35中的元素应具有TypeB,等等。但是,总对象数和每种类型的对象的数量是动态的。
I need to compare type of each object to the object that came before it and display or not display a different div within the one shown above dependent upon if those two values differ. 我需要将每个对象的类型与之前的对象进行比较,并根据上述两个值是否不同,在上面显示的那个对象内显示或不显示不同的div。
Iteration of groupsList occurs in the template due to the ngFor directive. 由于ngFor指令,在模板中进行groupsList的迭代。 As such I assume that I have to do this comparison there in the template as well rather than in my component.
因此,我假设我必须在模板中而不是在组件中进行此比较。
Is the right way of doing this to create a couple ng-containers and do two way binding to two variables in my component named something like priorType and currentType? 是这样做的正确方法,以创建一对ng容器,并以双向方式绑定到我的组件中的两个变量,如Priority和currentType这样的变量吗?
Updated with short solution : 更新了简短的解决方案 :
<div *ngFor="let g of groupsList; let i=index">
<div *ngIf="(i==0) || (i>0 && g.type != groupsList[i-1].type)">
Here's sample html where you can compare an object with it's previous object and show different div
based on the comparison. 这是示例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>
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.