Search code examples
angularangular-materialangular-reactive-formsmat-form-fieldmat-input

Angular set mat-input to error state after http error response


is there a possibility to set mat-input in error state after http error response? On submit of form from code below im sending an http request and i would like to show the mat-error but it shows only when input is in error state and i don't know how to set it "manualy" after error response

<form [formGroup]="exampleForm" (ngSubmit)="onSubmit()">
  <mat-form-field>
    <input matInput placeholder="placeholder" formControlName="Input" required>
    <mat-error *ngIf="variable">error message</mat-error>
  </mat-form-field>
</form>


Solution

  • serviceClass:

    export class serviceClass{
        private url: string = 'your url'// your http request url
    
        constructor(private http: HttpClient) { }
    
        callApi() {
            return this.http.get(this.url);
        }
    }
    

    componentClass: while subscribing http request if you get error in response can set the errorVariable true.

    export class componentClass{
            private url: string = 'your url'
            public errorVariable:boolean;
            constructor(private service: serviceClass) { }
    
            getApi() {
                return this.service.callApi().subscribe(
                  (response:string)=>{
                    console.log(response);
                 },
                (error)=>{
                    console.error(error);
                    this.errorVariable=true;
                }
                );
            }
        }
    

    htmlTemplate:

    <mat-error *ngIf="errorVariable">error message</mat-error>