I have a radio group that I want to set the value of from my component code. However I cannot seem to set the intial value using [(ngModel)]. I dont get any errors or anything to show why it is not showing the radio button selected.
<div class="form-group">
<mat-radio-group [(ngModel)]="selectedStatus" formControlName="completed">
<mat-radio-button [value]="1">Call Complete</mat-radio-button>
<mat-radio-button [value]="2">Call Incomplete</mat-radio-button>
</mat-radio-group>
</div>
Component code snippets:
selectedStatus: Array<string>;
private initForm() {
this.eventEditForm = new FormGroup({
'completed': new FormControl()
});
this.selectedStatus = this.data[0].completed;
}
this.data[0].completed returns 1 or 2 from a data service.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value.
Your ngModel is not working because it's not a part of your NgModule yet. You have to tell the NgModule that you have authority to use ngModel throughout your app, You can do it by adding FormsModule into your app.
To fix Can't bind to 'ngModel' since it isn't a known property of 'input' error in Angular applications we have to import FormModule in app. module. ts file. If you are using FormBuilder class to create reactive form we have to import ReactiveFormsModule as well to avoid below error.
Your variable selectedStatus
should not be a array of strings, it should be a number, change it as.
selectedStatus: number ;
WORKING STACKBLITZ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With