ngClass mat-radio-button 如果选中/Angular

ngClass mat-radio-button if checked / Angular

我正在迭代这些单选按钮:

planes = [
  { nombre: '3 días', costo: 0 },
  { nombre: '7 días', costo: 0 },
  { nombre: '15 días', costo: 0 }
];

我只想添加一个 class 已选中的 [ngClass]="{'border border-secondary': checked}"

但我没有得到任何结果:

<mat-radio-group class="d-flex flex-column" formControlName="plan">
  <mat-radio-button class="my-1 border rounded p-3" *ngFor="let plan of planes; let i = index" [ngClass]="{'border border-secondary': checked}" [value]="plan.nombre">
    <div class="d-flex justify-content-between">
      <span class="h4 w-100">{{plan.nombre}}</span>
      <span class="text-muted">{{plan.costo | currency : 'S/ '}}</span>
    </div>
  </mat-radio-button>
</mat-radio-group>

您可以参考带有 template reference variable #btn and get the value of its checked property. Depending if you are adding one or several classes to the checked button, you can use one of the following class binding 语法的按钮:

<mat-radio-button #btn [class.border-secondary]="btn.checked" ... >
<mat-radio-button #btn [ngClass]="{ 'border border-secondary': btn.checked }" ... >

有关演示,请参阅 this stackblitz


如果组件class属性绑定了radio组(如[(ngModel)]="selectedNombre"),可以通过绑定值与radio的比较来判断单选按钮是否被勾选按钮值:

<mat-radio-button [class.border-secondary]="selectedPlane === plane.nombre" ... >
<mat-radio-button [ngClass]="{ 'border border-secondary': selectedPlane === plane.nombre }" ... >

另一种方法是利用 Angular Material 已经将 class mat-radio-checked 添加到所选单选按钮这一事实。然后,您可以在 CSS:

中添加其他样式
mat-radio-button.border.mat-radio-checked {
  border-color: red;
}

有关演示,请参阅 this stackblitz