Angular*ng如果未使用组件方法更新



使用函数显示/隐藏*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,您可以提供自定义ErrorStateMatchers,它可以访问显示错误消息所需的数据。下面是一个简化的例子;

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错误,你会发现你的ngIf可能正在工作;

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

可以按照此处的描述进行设计

解决方法是将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>

最新更新