How to bind default value in mat-radio-group angular reactive forms
In my case it needs to active option 01 as default selection. It is working with checked=true property, but value is not binding with the formControlName="options", it is binding when user select any option. if no any user selection options value shows as "null".
<div class="row">
<mat-radio-group formControlName="options">
<mat-radio-button checked=true value="1">Option 01</mat-radio-button>
<mat-radio-button value="2">Option 02</mat-radio-button>
</mat-radio-group>
</div>
Please kindly help me to resolve this issue. Thank you.
What you want to do is to remove the checked
and instead set the preselected value to your formControl
, so when you build your form:
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
options: ['1']
})
}
and then you just remove the checked
attribute:
<mat-radio-group formControlName="options">
<mat-radio-button value="1">Option 01</mat-radio-button>
<mat-radio-button value="2">Option 02</mat-radio-button>
</mat-radio-group>
Alternate way:
this.optionFormGroup = new FormGroup({
options: new FormControl('1'); // the value type (string) should match
})
--
<div class="row" [formGroup]="optionFormGroup">
<mat-radio-group formControlName="options">
<mat-radio-button checked value="1">Option 01</mat-radio-button>
<mat-radio-button value="2">Option 02</mat-radio-button>
</mat-radio-group>
</div>
This will default select "yes" option from radio button options.
<form [formGroup]="optionsFormGroup">
<mat-grid-list cols="1" rowHeight="75px">
<mat-grid-tile>
<label>Option</label>
<mat-radio-group formControlName="statusOptions" class="m-l-5">
<mat-radio-button class="m-r-5" value="yes">Yes</mat-radio-button>
<mat-radio-button class="m-r-5" value="no">No</mat-radio-button>
</mat-radio-group>
<mat-icon class="info-icon">help_outline
</mat-icon>
</mat-grid-tile>
</mat-grid-list>
</form>
initFormControls() {
this.optionsFormGroup = this.formBuilder.group({
statusOptions: ['yes'],
});
}