angular material 在 mat-radio-group 上添加名称后,mat-radio-button 默认检查不起作用

angular material mat-radio-button default checked not working after adding name on mat-radio-group

在带有 angular material 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'">

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

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

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

您将需要 [(ngModel)] 附近的名称="your_name",然后选中的 属性 将不起作用,但您可以这样做。

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

要在没有名称的情况下仅使用对象工作,则集合应该是集合的一个实例才能工作并添加 [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>