angular - 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,因为它用于动态网格
解决方案
该<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>
推荐阅读
- c# - 使用 MS-Graph API 搜索特定邮件时出现问题
- vue.js - 使用 Vue apollo 无限加载失败的查询
- javascript - 通过 chrome 扩展程序登录 laravel nova 网络应用程序。419 错误 csrf 令牌不匹配
- scala - 新 StreamingContext 上的 NoSuchMethodError
- regex - 在 Google Sheet 中提取 url 域根目录
- excel - 如何使用两个条件执行 sumproduct?
- javascript - 当嵌入到 expo-av 的视频组件中时,expo-camera 返回的视频 url 给出了空白屏幕
- excel - 在单元格中使用内部颜色来选择要存储在字符串中的电子邮件地址
- javascript - 使用时位置不突出显示
- python - 如何清除 tkinter 的标签文本