How to bind default value in mat-radio-group angular reactive forms
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 is look like other answers, but uses boolean values
ts
form: FormGroup = this.formBuilder.group({
enable: ['']
});
ngOnInit(): void {
this.form.get('enable').setValue(false);
}
template
<mat-radio-group aria-label="Select an option" formControlName="enable">
<mat-radio-button [value]="true" color="primary">Enable</mat-radio-button>
<mat-radio-button [value]="false" color="primary" class="radio">Disable</mat-radio-button>
</mat-radio-group>
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'],
});
}