0
votes

In an Angular 5 app with angular material 5.2.5, when using this code the radio button default checked is working but there is an error in console

Code :

<mat-radio-group [(ngModel)]="collection">
  <mat-radio-button class="collectionRadioButton" 
   *ngFor="let coll of collections" 
   [value]="coll.endPoint" 
   [checked]="coll.isDefault" 
   (change)="clearResults()">
  {{coll.label}}
  </mat-radio-button>
</mat-radio-group>

Error in Chrome console :

ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

Example 1: <input [(ngModel)]="person.firstName" name="first">   
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
at Function.TemplateDrivenErrors.missingNameException (forms.js:5891)
at NgModel._checkName (forms.js:6244)
at NgModel._checkForErrors (forms.js:6217)
at NgModel.ngOnChanges (forms.js:6099)
at checkAndUpdateDirectiveInline (core.js:12407)
at checkAndUpdateNodeInline (core.js:13935)
at checkAndUpdateNode (core.js:13878)
at debugCheckAndUpdateNode (core.js:14771)
at debugCheckDirectivesFn (core.js:14712)

But when adding a name to mat-radio-group

<mat-radio-group [(ngModel)]="collection" [name]="'aList'">

then the radio button list is still correctly generated but the default checked is no longer working ...

3
Full code? Looks like your code is nested in a <form> - Edric

3 Answers

7
votes

You will need the name="your_name" near [(ngModel)], then the checked property will not work but you can do like this.

<form>  
 <mat-radio-group [(ngModel)]="radioOptions" name="radioButtons">
    <mat-radio-button [value]="'TEST1'">TEST1</mat-radio-button>
    <mat-radio-button [value]="'TEST2'">TEST2</mat-radio-button>
</mat-radio-group> </form>

  import { FormsModule } from '@angular/forms';
  export class ConfigurazioneComponent implements OnInit {
     radioOptions: string = 'TEST1'; 
  }
0
votes

If im not mistaken, you can't use [name]="''" but name=""

name="{{aList}}" // this should work just fine if that aList was variable else
name="aList" // if its a string
0
votes

To work wihout name and just with object, then collection should be an instance of collections to works and add [ngModelOptions]="{standalone: true}" attribute.

Example in your code: Component :

  this.collection = this.collections.find(x => x.isDefault)

Template:

<mat-radio-group [(ngModel)]="collection">
    <mat-radio-button class="collectionRadioButton" 
                      *ngFor="let coll of collections" 
                      [value]="coll" 
                      (change)="clearResults()"
                      [ngModelOptions]="{standalone: true}" >
       {{coll.label}}
    </mat-radio-button>
  </mat-radio-group>