Home > other >  Angular, add unique class to ngFor loop while having an existing ngClass
Angular, add unique class to ngFor loop while having an existing ngClass

Time:11-03

I have a ngFor loop and I want to assign a unique class to each element but I have an already existing ngClass condition.

  <div  *ngFor="let info of list" [ngClass]="{active: isActive(info)}">
    <div ></div>

  </div>

I tried adding [ngClass]="{active: isActive(info), info.name}" but it didn't work for me.

CodePudding user response:

Is info.name a class you want to apply? If so move it over to your class attribute instead:

  <div 
     
    *ngFor="let info of list" 
    [ngClass]="{active: isActive(info)}">
      <div ></div>
  </div>

CodePudding user response:

If you use ngClass you should provide a class name (string type)

In your case, in your.component.css

.activeClassName {
  active: true; //or whatever you want
}

in your.component.html (if isActive(info) is a correct method)

<div  *ngFor="let info of list" [ngClass]="isActive(info) ? 'activeClassName' : ''">
 <div ></div>
</div>

In that way you provide correctly a string

  • Related