【问题标题】:angular material mat-radio-button default checked not working after adding name on mat-radio-group在 mat-radio-group 上添加名称后,角度材料 mat-radio-button 默认检查不起作用
【发布时间】:2018-10-11 17:35:20
【问题描述】:

在使用 Angular 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'">

那么单选按钮列表仍然正确生成,但默认选中的不再起作用...

【问题讨论】:

  • 完整代码?看起来您的代码嵌套在 &lt;form&gt;

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


【解决方案1】:

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

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

【讨论】:

  • 已经尝试过了,它不适用于 name="{{aList}}" 或 name="aList"
【解决方案2】:

您将需要 [(ngModel)] 附近的 name="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'; 
  }

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2021-07-26
      • 1970-01-01
      • 2020-08-07
      • 2019-05-30
      相关资源
      最近更新 更多