1

How do I add different classes for the inner elements in an ngFor loop in Angular 4? Say, I have a snippet:

<div *ngFor="let article of articles">
  <div>
    <h3>{{article.name}}</h3>
    <p>{{article.body}}</p>
  </div>
</div>

So I have 2 questions: how do I add different classes to the h3 elements in every generated article based on their order (first, second, third) and how do I add classes to the h3 elements based on odd-even order?

2
  • 1
    just as a side note : you are setting the same id for all your loop divs, namely the string "article", which could get you into other errors. Commented Oct 5, 2017 at 16:33
  • Thanks, that actually shouldn't be there Commented Oct 6, 2017 at 20:29

1 Answer 1

4

You can get the index, odd, and even of the current iteration in the ngForOf, combine that with ngClass and you can set the class.

<div *ngFor="let article of articles; index as i; even as isEven; odd as isOdd">
  <div id="article">
    <h3 [ngClass]="{'odd': isOdd, 'even': isEven}">{{article.name}}</h3>
    <p>{{article.body}}</p>
  </div>
</div>

You do not mention how you want to use the index/position so there is no code for that. I am sure you can figure that part out though based on the sample code above and documentation.


As @Paco0 also pointed out maybe you meant id="article" to be id="{{article.id}}" or something similar?

Sign up to request clarification or add additional context in comments.

3 Comments

isEven is default function?
as long as id is just an html attribute, "article.id" will be the string "article.id", not the actual article id. Need something like id="{{article.id}}" to be evaluated.
@artgb - no, even is and isEven is an alias for even.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.