Angular 添加类=";“世界其他地区”;角js中的每5项
我是新来的Angular 添加类=";“世界其他地区”;角js中的每5项,angular,Angular,我是新来的Angular我想在5项中的每一项中添加class=“row”我如何在父div中使用数组的索引我可以这样使用[ngClass]=“{row:index%5==0} <div class="grid-on"> <div [ngClass]="{row:index%5===0}`> <div class="col-1-of-5" *ngFor="let category of categories;let index=index">
Angular
我想在5项中的每一项中添加class=“row”
我如何在父div中使用数组的索引我可以这样使用[ngClass]=“{row:index%5==0}
<div class="grid-on">
<div [ngClass]="{row:index%5===0}`>
<div class="col-1-of-5" *ngFor="let category of categories;let index=index">
<div class="item-box">
<img src={{category.imagePath}} alt="" class="item box__img">
<h3 class="heading-quaternary">{{category.name}}</h3>
<p>{{category.description}}</p>
</div>
</div>
</div>
</div>
试试这个
<div class="grid-on">
<div class="col-1-of-5" *ngFor="let category of categories;let index=index" [ngClass]="{row:index%5===0}`>
<div class="item-box">
<img src={{category.imagePath}} alt="" class="item box__img">
<h3 class="heading-quaternary">{{category.name}}</h3>
<p>{{category.description}}</p>
</div>
</div>
</div>
如果对所有类别进行循环,则每个类别都会有一个div,有些类别会有row类,有些则不会。我认为您想要的是对每五个类别都有一个row类的div。然后对我来说,最好的方法是计算typescript中所需的行数,并将行数设置为数组元素的数组。然后,您可以使用该数组在具有row类的div上循环。
然后,为了为每行获取五个元素,您可以编写一个方法,该方法基于带有row类的div索引只返回五个元素。类似于,如果索引为0,则将类别[0]返回给类别[4],如果为1,则将类别[5]返回给类别[9],依此类推。请查看以下代码:
在TypeScript中:
rowNumber: number[];
constructor() {
this.rowNumber = [];
for (let i = 0; i < this.categories.length / 5; i++) {
this.rowNumber.push(i);
}
}
getCurrentCategories(currentIndex) {
let item = [];
let firstIndex = currentIndex * 5;
for (let i = 0; i < 5; i++) {
let nextIndex = firstIndex + i;
if (this.categories[nextIndex]){
item.push(this.categories[nextIndex]);
}
}
return item;
}
rowNumber:number[];
构造函数(){
this.rowNumber=[];
for(设i=0;i
在html中:
<div class="row" *ngFor="let row of rowNumber; let i=index">
<div class="col-1-of-5 u-margin-t-small" *ngFor="let category of getCurrentCategories(i)">
<div class="item-box">
<img src={{category.imagePath}} alt="" class="item-box__img">
<h3 class="heading-quaternary">{{category.name}}</h3>
<p>{{category.description}}</p>
</div>
</div>
</div>
{{category.name}
{{category.description}}
请注意,可以在获取categories数组的任何方法中设置行数。但为了简单起见,我只在构造函数中设置行数。ng class=“($index+1)%5?”:行'”(0在javascript中已经是错误的,因此不需要===0)[ngClass]=“{'row':索引%5==0}不要忘记引号