Mat 错误不显示自定义验证器的错误,但模板显示错误

Mat error is not displaying error for custom validators but template is displaying error

app.component.html

    <div class="col-sm-3">
                            <mat-form-field class="col-sm-3" appearance="outline"
                                class="example-full-width input-small-size d-block">
                                <mat-label>Personal Phone 1
                                </mat-label>
                                <input matInput formControlName="phonePersonal01" type="number">
                                <mat-error *ngIf="personalform.errors?.invalidPhoneMatch">
                                    Enter different numbers.
                                </mat-error>
<!-- This error is not displaying -->
                            </mat-form-field>{{personalform.errors|json}} 
    <!-- Output is : { "invalidPhoneMatch": true }-->
                        </div>

app.component.ts

personalform = this.fb.group({

        
        
        phno: ['', [Validators.required, Validators.pattern('\+{0,1}[0-9]{10,12}')]],
        phonePersonal01: ['', [Validators.required, Validators.pattern("\+{0,1}[0-9]{10,12}")]],
        phonePersonal02: ['', [Validators.required, Validators.pattern("\+{0,1}[0-9]{10,12}")]],
    
      }, { validator: this.checkContactNumbers }
      );

...

checkContactNumbers(c: FormBuilder) {
    //safety check
    console.log(c[`value`][`phno`]);
    console.log(c[`value`][`phonePersonal01`]);

    if (c[`value`][`phno`] == c[`value`][`phonePersonal01`])
    {
      console.log('this ran');
      
      return { invalidPhoneMatch: true }
    }
  
  }

我正在尝试自定义验证器。 html 表单 json 管道正在显示输出,但 mat 错误未显示输出。

由于这是您自己的错误,您无法将其作为控件的 属性 进行访问。改为这样做:

<mat-error *ngIf="personalform.hasError('invalidPhoneMatch')">

其次。您构建错误对象的方式也是错误的。你必须有这个结构:

return {invalidPhoneMatch: {value: true}};

第二种方法

使验证器成为表单域控制器的验证器。

personalform = this.fb.group({
    phno: ['', [Validators.required, Validators.pattern('\+{0,1}[0-9]{10,12}')]],
    phonePersonal01: ['', [Validators.required, this.checkContactNumbers, Validators.pattern("\+{0,1}[0-9]{10,12}")]],
    phonePersonal02: ['', [Validators.required, Validators.pattern("\+{0,1}[0-9]{10,12}")]],
});