Search code examples
angular-materialangular7

Checked attribute not working in mat-radio-button


I am creating a radio button with the checked property but it's not showing selected

<mat-radio-group name="radioOpt1" [(ngModel)]="selectedRadio" [ngModelOptions]="{standalone: true}" (change)="radioChange($event)">
<mat-radio-button value="own" checked name="own">Own</mat-radio-button>
<mat-radio-button value="competitor" name="own">competitor</mat-radio-button> </mat-radio-group>

I want the first radio button to be checked by default


Solution

  • If using ngModel then you need to pass value of radio-button to ngModel.

    <mat-radio-group name="radioOpt1" [(ngModel)]="selectedRadio" 
       [ngModelOptions]="{standalone: true}" (change)="radioChange($event)">
      <mat-radio-button value="own" name="own">Own</mat-radio-button>
      <mat-radio-button value="competitor" name="own">competitor</mat-radio-button> 
    </mat-radio-group>
    

    and ts file

     selectedRadio = 'own'; //default value
    
     radioChange(e){
       console.log(this.selectedRadio)
     }
    

    or dynamically populated

     <mat-radio-group name="radioOpt1" [(ngModel)]="selectedRadio"
        [ngModelOptions]="{standalone: true}" (change)="radioChange($event)">
       <mat-radio-button *ngFor="let but of list" [value]="but.id" name="own" >
          {{but.name}}
       </mat-radio-button>
     </mat-radio-group>
    

    ts file

      list = [{ "name": "own", id: "own"},{ "name": "competitor", id: "competitor"}];
    
      selectedRadio =this.list[0].id;