简体   繁体   中英

ngClass mat-radio-button if checked / Angular

I am iterating these mat-radio-button:

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

I want to add a class only for which it is selected: [ngClass]="{'border border-secondary': checked}"

but I don't get any results:

<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>

You can refer to the button wih a 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 syntaxes:

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

See this stackblitz for a demo.


If a component class property is bound to the radio group (eg [(ngModel)]="selectedNombre" ), you can determine if a radio button is checked by comparing the bound value to the radio button value:

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

An alternative is to take advantage of the fact that Angular Material already adds the class mat-radio-checked to the selected radio button. You can then add additional styling in CSS:

mat-radio-button.border.mat-radio-checked {
  border-color: red;
}

See this stackblitz for a demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM