Angular 2+ material mat-chip-list formArray validation
The problem is that the chipList's errorState
isn't set to true
when the chipList's FormArray
status is INVALID
.
I'm facing the same problem and don't know why this isn't working out of the box or how this can be achieved implicitly with the chipList's form being a FormArray
.
As a workaround you can listen to status changes from the FormArray
and set the chipList's errorState
manually:
@ViewChild('chipList') chipList: MatChipList;
ngOnInit() {
this.myForm.get('names').statusChanges.subscribe(
status => this.chipList.errorState = status === 'INVALID'
);
}
https://stackblitz.com/edit/angular-4d5vfj-gywxjz
Unfortunately, it's not possible to use any of Angular's predefined validators because they are not designed to work with arrays. I manage to do it with the help of this article:
https://www.dev6.com/Angular_Material_Chips_with_Reactive_Forms_and_Custom_Validation
To be able to get the validation working on a mat-chip-list
we have to bind both the mat-input
and mat-chip-list
with same FormControl
like below
Working Stackblitz link here
<form [formGroup]='group'>
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList
required
formControlName="newFruit">
<mat-chip *ngFor="let fruit of fruits"
(removed)="remove(fruit)">
{{fruit.name}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
<input placeholder="New fruit..."
formControlName="newFruit"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)" required>
</mat-chip-list>
<!-- add mat-error -->
<mat-error *ngIf="group.controls.newFruit.hasError('required')">required!</mat-error>
</mat-form-field>
</form>