mat-list的formControlName给出“ mat-form-field必须包含MatFormFieldControl”

时间:2019-11-29 06:08:21

标签: angular angular-material angular-reactive-forms angular-components mat-list

StackBlitz (runnable example)

组件的角度HTML模板

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput placeholder="name" formControlName="name">
  </mat-form-field>

  <mat-form-field>
    <mat-list formControlName="foldersList">
      <mat-list-item *ngFor="let folder of folders"><h4 mat-line>{{folder.name}}</h4></mat-list-item>
    </mat-list>
  </mat-form-field>
</form>

Angular TypeScript组件

export class MyComponent {
  folders = [ { name: 'Photos', updated: new Date('1/1/16') } ];

  myForm: FormGroup = this.fb.group({
    name: ['', Validators.required],
    foldersList: 
           new FormControl([]),
           // new FormArray([]),
           // ['', Validators. Validators.required],
           // this.fb.array([], [Validators.required]),
  });

  constructor(private fb: FormBuilder) {}
}

错误

Error: No value accessor for form control with name: 'foldersList'
Error: mat-form-field must contain a MatFormFieldControl.

1 个答案:

答案 0 :(得分:2)

mat-listmat-selection-list组件未实现MatFormFieldControl接口。这就是为什么不能在mat-form-field内部使用它们的原因。

这是上面示例的工作叉:https://stackblitz.com/edit/angular-xijtrv-yzpsmj

只需将mat-list替换为mat-selection-list,然后除去包裹它的mat-form-field