首页 > 解决方案 > Angular *ngIf 未使用组件方法更新

问题描述

当使用功能显示/隐藏*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,因为它用于动态网格

标签: angularangular-ng-if

解决方案


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

如果您尝试使用 mat-error 以外的其他 html 标记,您将看到您的 ngIf 可能正在工作;

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

推荐阅读