Sergio Cano
Sergio Cano

Reputation: 760

individual ngClass in a ngFor loop, angular 6

I am trying to change the class of a specific position in my *ngFor, for example:

HTML

<table>
 <tr *ngFor="let article of articles; let i = index">
  <td>
    <input type="text" name="name" [(ngModel)]="articles[i].name" [ngClass]="{'is-valid': wrongArticle == false }" (change)="checkArticle(i)" >
  </td>
 </tr>
</table>

TS

articles = [{name: ""}, {name: ""}, {name: ""}]
wrongArticle: boolean = true;

 checkArticle(i){
  if(this.articles[i].name != ""){
  this.wrongArticle = false;
  }
 }

So... my problem is... when i type something in any input... the class 'is-valid' is applied in every input... how can i apply 'is-valid' just in the correct input?

Upvotes: 2

Views: 2758

Answers (1)

Ajay Ojha
Ajay Ojha

Reputation: 390

Instead of defining 'wrongArticle' globally. try to use 'wrongArticle' property in the article row. I have created a working sample application stackblitz

Here is the ts code

 articles = [{name: ""}, {name: ""}, {name: ""}]
wrongArticle: boolean = true;

 checkArticle(article:any){
  if(article.name != ""){
  article.wrongArticle = false;
  }
 }

here is the html code

<table>
 <tr *ngFor="let article of articles; let i = index">
  <td>
    <input type="text" name="name" [(ngModel)]="articles[i].name" [ngClass]="{'is-valid': article.wrongArticle == false }" (change)="checkArticle(article)" >
  </td>
 </tr>
</table>

Upvotes: 2

Related Questions