Angular *ngIf 未使用组件方法更新

Angular *ngIf not updated with component method

当使用 show/hide 和 *ngIf 的函数时,块不会在 html 中更新。 渲染块以检查值 ({{contactInfoValid(contact)}}) 是否已正确更新时,*ngIf 未被触发

HTML

<mat-form-field>
            <input matInput  type="text"
                      [(ngModel)]="contact.info" required>               
            <mat-error *ngIf="contactInfoValid(contact) == false">
               email not correct
            </mat-error>
        </mat-form-field>

组件

  contactInfoValid(contact) {
    if (contact.hasValidInfo) {
       return true;
       }

    return false;
  }

mat-error 从未显示。

在此特定情况下不能使用 FormControl,因为它用于动态网格

<mat-error> 组件需要 ErrorStateMatcher 才能显示任何内容。这里有一篇关于此的好文章; https://itnext.io/materror-cross-field-validators-in-angular-material-7-97053b2ed0cf

简而言之,您需要在要验证的表单字段上指定 [errorStateMatcher]="myErrorStateMatcher"

<mat-form-field>
   <input matInput type="text" [(ngModel)]="contact.info" required
        [errorStateMatcher]="myErrorStateMatcher">
   <mat-error *ngIf="contactInfoValid(contact) == false">
       email not correct
   </mat-error>
</mat-form-field>

通常 ErrorStateMatcher 与 FormControls 配合使用,但如果您想使用 ngModel,您可以提供自定义 ErrorStateMatcher,它可以访问显示错误消息所需的数据。下面是一个简化的例子;

export class RuleErrorStateMatcher<T> implements ErrorStateMatcher {
    constructor(private editControl: IValidatableEditControl<T>) { }

    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        return this.editControl && this.editControl.model && !this.editControl.model.isValid;
    }
}

export interface IValidatableEditControl<T> {
    model: ValidationGeneric<T>;
}

export class ValidationGeneric<T>   {
    public value: T;
    public isValid: boolean;
}

如果你尝试另一个 html 标签而不是 mat-error 你会发现你的 ngIf 可能正在工作;

<span *ngIf="contactInfoValid(contact) == false">
        email not correct
</span>

它可能是按照描述设计的 here

解决方法是像这样添加 FormControl,而不是绑定到 [(ngModel)]

email = new FormControl('', [Validators.required, Validators.email]);

<div class="example-container">
  <mat-form-field appearance="fill">
    <mat-label>Enter your email</mat-label>
    <input matInput placeholder="pat@example.com" [formControl]="email" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>