Sumchans
Sumchans

Reputation: 3774

Angular Material mat-chip validation

How do I validate if the user has selected a chip in the mat-chip-list and also only when the user selects a chip form should become valid. Right now I have the validators.required set on the control, but it doesn't work. This is what I have done so far:


HTML

<mat-chip-list formControlName="packageName">
   <mat-chip *ngFor="let pkg of packages" selected="true" style="background-color:#8d6e63">
        {{pkg.value}}
   </mat-chip>
</mat-chip-list>

TS

ngOnInit() {
  this.form = new FormGroup({
    'packageName': new FormControl('', Validators.required),
})

Upvotes: 8

Views: 13024

Answers (2)

Jonathan
Jonathan

Reputation: 4709

Here is what I did:

... (matChipInputTokenEnd)="add($event, postForm.get('tags'))" />
export interface Tag {
  name: string;
}
...

tags: Tag[] = [];
...

add(event: MatChipInputEvent, form: AbstractControl | null): any {
  // add tag from keyboard
  const input = event.chipInput;
  const value = event.value;
  // Reset the input value
  if (input) {
    input.clear();
  }
  // Add tag
  if ((value || '').trim()) {
    this.tags.push({ name: tag.trim() });
  }

  // set value for validation  <--- key code here
  form?.setValue(this.tags);

  return this.tags;
}

The key here is adding a blank value or an empty value to the actual form control.

UPDATE: - I also found another version using form groups.

Upvotes: 0

ibenjelloun
ibenjelloun

Reputation: 7733

You could use form.status to get the form status VALID or INVALID or form.controls.packageName.errors to get an array of the formControl errors or null if no errors.

Here is a running example using your code.

Upvotes: 5

Related Questions