Search code examples
angularangular-materialangular-reactive-formsangular-componentsmat-list

formControlName for mat-list gives 'mat-form-field must contain a MatFormFieldControl'


StackBlitz (runnable example)

Angular HTML template for Component

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

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) {}
}

Errors

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

Solution

  • The mat-list and mat-selection-list components do not implement the MatFormFieldControl interface. Which is why they can not be used inside a mat-form-field.

    Here's a working fork of the above example: https://stackblitz.com/edit/angular-xijtrv-yzpsmj

    Just replaced mat-list with mat-selection-list and removed the mat-form-field that wrapped it.