角材料输入自定义垫错误问题

时间:2020-08-31 10:56:06

标签: angular angular-material

我有一个带有formControl和自定义垫错误的角材输入。当我执行mat-error时,即使没有重点注意,它也看起来像Invalid。怎么了?

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}]

1 个答案:

答案 0 :(得分:0)

首先,您已经创建了一个自定义错误状态匹配器,绑定了输入,但是您已经在app.module.ts中将默认的ErrorStateMatcher与ShowOnDirtyErrorStateMatcher进行了切换。

这是预期的主意吗?您能请您扩展一下思路吗?

第二个输入看起来很奇怪。似乎有错误(因为您已经将光标对准了焦点,但是占位符没有过渡到标签。您检查控制台了吗?好像有些东西没有正确安装,或者您忘记了导入MatInputModule?

相关问题