Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

angular - NgFor index change class every 3 items. Math Problem?

I have 3 CSS classes which colour a mat-icon which I use in an NgFor of news Items. I want the colours of each item to change on each item in blocks of 3. So I need the 1st and 4th to be the same class the 2nd and 5th and so on. The only way I can do this right now is like so:

<mat-icon *ngIf="i == 0" class="news-icon-1">language</mat-icon>
<mat-icon *ngIf="i == 1" class="news-icon-2">language</mat-icon>
<mat-icon *ngIf="i == 2" class="news-icon-3">language</mat-icon>
<mat-icon *ngIf="i == 3" class="news-icon-1">language</mat-icon>
<mat-icon *ngIf="i == 4" class="news-icon-2">language</mat-icon>
<mat-icon *ngIf="i == 5" class="news-icon-3">language</mat-icon>
<mat-icon *ngIf="i == 6" class="news-icon-1">language</mat-icon>
<mat-icon *ngIf="i == 7" class="news-icon-2">language</mat-icon>
<mat-icon *ngIf="i == 8" class="news-icon-3">language</mat-icon>

There must be a better way to do this, probably using math but I'm not sure what that might be. Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use $index to solve your problem

<ng-container *ngFor="let item of items; let index = index;">
 <mat-icon *ngIf="i == index" class="news-icon-{{i%3 + 1)}}">language</mat-icon>
</ng-container>

or, if you need more control, you could use ngClass:

<ng-container *ngFor="let item of items; let index = index;">
 <mat-icon *ngIf="i == index" [ngClass]="{'news-icon-1': i%3==0, 'news-icon-2': i%3==1, 'news-icon-3': i%3==2}">language</mat-icon>
</ng-container>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...