使用 ngfor、ngClass、ngChange 根据选中的单选按钮 angular 更改 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>

此处 'isChecked' class 应用于所有基于输入的标签,但 class 即使我 select 另一个选项也不会被删除。

我试过这种方法,但如果未选中输入,它不会删除 class。

我创建了一个 slackblitz 示例 https://stackblitz.com/edit/angular-ngclass-ngfor-change

提前致谢

试试这个:

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

我发现这个解决方案有效。

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'];
}

}