4
votes

Stackblitz example link

I am using angular material - mat-autocomplete inside form. I want to show red highlight text and border color to the input field & mat-error message for matAutocomplete input when form is invalid. Suggestion for reactive or template driven form will work

Issue screenshot

4

4 Answers

0
votes

chips-autocomplete-exaple.ts file

import {FormControl, Validators} from '@angular/forms';
fruitCtrl = new FormControl(null, Validators.required);

instead of null, you can pass an initial value,

chips-autocomplete-exaple.html file

  <span *ngIf="fruitCtrl.invalid && fruitCtrl.touched">
     required
   </span>

similary to add Error borders you can use [ngClass]

Hope this helps.

0
votes

Add template reference variable to mat-form-field

<mat-form-field #tagsField>
        <mat-label><strong>Tags</strong></mat-label>
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let tag of tags" [selectable]="selectable" [removable]="removable"
            (removed)="remove(tag)" required>
            {{tag}}
            <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
          </mat-chip>
          <input placeholder="eg.(C#,VB)" #tagInput [formControl]="frmAskQuestion.controls['tags']"
            [matAutocomplete]="auto" [matChipInputFor]="chipList"
            [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur"
            (matChipInputTokenEnd)="add($event)" required>
        </mat-chip-list>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)" required>
          <mat-option *ngFor="let tag of filteredTags" [value]="tag">
            {{tag}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>

and then is ts page

  if (!this.frmAskQuestion.valid) {
  this.tagsField._elementRef.nativeElement.classList.add("mat-form-field-invalid");
}
else{
  this.tagsField._elementRef.nativeElement.classList.remove("mat-form-field-invalid");
}

Note : This not the best way but i couldn't find any other way

0
votes

I did this.

scss

/deep/ .mat-form-field-invalid {
  .mat-form-field-underline {
    background-color: #f44336;
  }

  .mat-form-field-label {
    color: #f44336;
  }
}
0
votes

As a workaround you can listen to status changes from the Form 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