Pan Markosian
Pan Markosian

Reputation: 101

Angular material Input custom mat error problem

I have an angular material input with an formControl and custom mat error. When I implement the mat-error it appears like this as an Invalid even when it is not focused. What's wrong with that?

enter image description here

Template.html

<form class="myform">
  <mat-form-field class="full-width">
    <mat-label>Project</mat-label>
      <input matInput
        [formControl]="projectNameControl"
        [errorStateMatcher]="matcher"
        autocomplete="off" type="text"
        placeholder="Type Project Name" >
        <mat-error *ngIf="projectNameControl.hasError('required')">
          Project name is <strong>required</strong>
        </mat-error>
     </mat-form-field>
</form>

Component.ts


import { FormControl, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));}}

  @Component({
    selector: 'app-upload-data',
    templateUrl: './upload-data.component.html',
    styleUrls: ['./upload-data.component.scss']
  })

  export class UploadDataComponent implements OnInit {
    /*Rest Code here*/
    projectNameControl = new FormControl('', [Validators.required]);    
    matcher = new MyErrorStateMatcher();
  }
}

app.module.ts

import {ErrorStateMatcher, ShowOnDirtyErrorStateMatcher} from '@angular/material/core';

providers: [{provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher}]

Upvotes: 0

Views: 1789

Answers (1)

Victor Muresanu
Victor Muresanu

Reputation: 166

First of all you have made a custom error state matcher, you've bound the input, and yet you have switched the default one ErrorStateMatcher with ShowOnDirtyErrorStateMatcher in app.module.ts.

Is this the intended idea? Can you please expand your thoughts?

Second your input looks odd. It looks like it has a error (because you have focused your cursor, but the placeholder didn't transition into label. Did you check the console? Seems to me like something didn't install properly, or maybe you forgot to import MatInputModule?

Upvotes: 1

Related Questions