在mat-radio-group上添加名称后,角度材料mat-radio-button默认选中不起作用

时间:2018-05-01 16:57:30

标签: angular forms angular-material angular5 radio-group

在角度材质5.2.5的Angular 5应用程序中,使用此代码时,单选的默认选项正在运行,但控制台中出现错误

代码:

<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>

Chrome控制台出错:

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)

但是在为mat-radio-group添加名称时

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

然后单选按钮列表仍然正确生成但默认选中不再有效......

3 个答案:

答案 0 :(得分:3)

你需要在[(ngModel)]附近使用name =“your_name”,然后check属性将不起作用,但你可以这样做。

<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'; 
  }

答案 1 :(得分:0)

如果我没记错,你不能使用[name]="''"而是name=""

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

答案 2 :(得分:0)

要使用名称且仅与对象一起工作,则collection应该是要工作的collection的实例,并添加[ngModelOptions] =“ {standalone:true}”属性。

代码示例: 组件:

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

模板:

<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>