Search code examples
angularngforng-class

change class based on radio button checked angular using ngfor, ngClass, ngChange


<div>
<label *ngFor="let article of articles; let i = index" [ngClass]="{'is-valid': isChecked}">
<input type="radio" name="name" (change)="isChecked = true">
  input{{i}}
</label>

Here the 'isChecked' class is applied for all labels based upon input, but the class is not removed even I select another option.

I tried this way, but it doesn't remove the class if input is unchecked. individual ngClass in a ngFor loop, angular 6

I created a slackblitz example https://stackblitz.com/edit/angular-ngclass-ngfor-change

Thanks in advance


Solution

  • I found this solution works.

    https://stackblitz.com/edit/angular-ngclass-ngfor-change-m2d1hy

    <div>
    <label *ngFor="let article of articles; let i = index" [ngClass]="[article.isChecked ? 'is-valid' : 'is-notvalid']">
    <input type="radio" name="name"  (change)="checked(i)" >
      input{{i}}
    </label>
    
    export class AppComponent  {
    name = 'Angular';
    articles = []
    isChecked: boolean = false;
    constructor(){
    this.articles.push({ "isChecked" : false});
    this.articles.push({ "isChecked" : false});
    this.articles.push({ "isChecked" : false});
    }
    test= "";
    checked(i){  
    this.articles.forEach(x=> x.isChecked = false);
    this.articles[i]['isChecked'] = !this.articles[i]['isChecked'];
    }
    
    }