Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NgModel to bind to radio group input for Angular Material

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.

like image 912
Eden WebStudio Avatar asked Dec 02 '17 16:12

Eden WebStudio


People also ask

What does [( ngModel )] mean?

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.

Can't bind to ngModel since it isn't a known property of Mat radio group?

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.

Can't bind to ngModel since it isn't a known property of input Ng?

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.


1 Answers

Your variable selectedStatus should not be a array of strings, it should be a number, change it as.

selectedStatus:  number ;  

WORKING STACKBLITZ

like image 80
Sajeetharan Avatar answered Nov 15 '22 05:11

Sajeetharan