使用单选按钮的双向绑定通过 [ngClass] 添加 class 到段落

Adding class via [ngClass] to paragraph using 2-Way binding of Radio Buttons

我在 home.css 中创建了 2 个 类,名称为 'male' 和 'female'。我制作了 2 个单选按钮,其值为 'male' 和 'female'。现在在我的段落中,我想在更改单选按钮的选择时更改段落的背景颜色。我想通过 Angular 中的 [ngClass] 实现此目的 4.

home.html

<input type="radio" name="gender" value="male" [(ngModel)]="genderType">Male 
<input type="radio" name="gender" value="female" [(ngModel)]="genderType">Female 
<p [ngClass]="genderType">This is 3rd paragraph.</p>

home.ts

genderType: string = "male";

home.css

.male{background:green;}
.female{background:violet;}

请帮我解决这个例子。目前,radio change 背景没有改变。

Note: I want to achieve this only with [ngClass] and Radio-buttons via 2-way binding.

这是基于您的代码的工作示例

模板

<input type="radio" name="gender" value="male" [(ngModel)]="genderType">Male 
<input type="radio" name="gender" value="female" [(ngModel)]="genderType">Female 

<p [ngClass]="genderType">This is 3rd paragraph.</p>

风格

.male{background:green;}
.female{background:violet;}

组件

export class AppComponent {
  public genderType: string = 'male';
}

stackblitz example

您也可以简单地动态评估 classes,如下所示:

<input type="radio" name="gender" value="male" [(ngModel)]="genderType">Male 
<input type="radio" name="gender" value="female" [(ngModel)]="genderType">Female 

<p class="{{genderType}}">This is 3rd paragraph.</p>

Angular 括号表达式会将您的 genderType 变量评估为字符串,并相应地更新它的 class。