8

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ibenjelloun, that worked like a charm. Have been struggling with this for almost couple days now. Didn't know it was this easy. Working example provided helped a lot. Thanks for putting that together for me.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.