由于某种原因,我的自定义Mat-erro无法正常工作。有人知道为什么吗?

时间:2019-06-18 01:31:27

标签: angular typescript angular-material

由于某些原因,mat-error无法正常工作。

我创建了一个自定义组件来处理我的错误。但是在渲染时,它无法正常工作。

那是页面

<mat-form-field appearance="outline">
  <input matInput placeholder="Enter your email" formControlName="ip" required>
  <app-form-field-error [form-control]="resourceForm.get('ip')"></app-form-field-error>
</mat-form-field>

那是我的自定义组件html

<mat-error >{{errorMessage}}</mat-error>

那是我的自定义组件ts

import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-form-field-error',
  templateUrl: './form-field-error.component.html',
  styleUrls: ['./form-field-error.component.css']
})
export class FormFieldErrorComponent implements OnInit {

  @Input('form-control')
  formControl: FormControl;

  constructor() {}

  ngOnInit() {}

  public get errorMessage(): string | null {
    if (this.mustShowErrorMessage()) {
      return this.getErrorMessage();
    } else {
      return null;
    }
  }


  private mustShowErrorMessage(): boolean {
    return this.formControl.invalid && this.formControl.touched;
  }

  private getErrorMessage(): string | null {

    if (this.formControl.errors.email) {
      return 'formato de email inválido';
    } else if (this.formControl.errors.minlength) {
      const requiredLength = this.formControl.errors.minlength.requiredLength;
      return `deve ter no mínimo ${requiredLength} caracteres`;
    } else if (this.formControl.errors.maxlength) {
      const requiredLength = this.formControl.errors.maxlength.requiredLength;
      return `deve ter no máximo ${requiredLength} caracteres`;
    }
  }

}

预期:http://prntscr.com/o35s9k

结果:http://prntscr.com/o35shk

1 个答案:

答案 0 :(得分:0)

我将第一个代码更改为:

<mat-error >
    <app-form-field-error [form-control]="resourceForm.get('ip')"></app-form-field-error> </mat-error>

并将app-form-field-error更改为:

<ng-container>{{errorMessage}}</ng-container>

现在像魅力一样工作!

谢谢!