当使用函数showhide与 *ngIf
在渲染该块时,检查该块的值({{contactInfoValid(contact)}}
)正确更新,则 *ngIf
没有被触发
超文本标记语言
<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.iomaterror-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>
这可能是设计上的原因,如上所述 此处
解决办法是在[(ngModel)]上添加类似这样的FormControl。
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="[email protected]" [formControl]="email" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
</div>