formControl.hasError('required') 和 formControl.errors 有什么区别?['required']
What is the difference between formControl.hasError('required') and formControl.errors?.['required']
我在 Angular 中有反应形式。我在论坛上看到了这两种方法。有人说我们应该避免在模板中调用函数。那么有什么区别,哪个是最佳实践?
<mat-error *ngIf="foundingYear?.hasError('required')">Founding Year is required</mat-error>
<mat-error *ngIf="foundingYear?.errors?.['required']">Founding Year is required</mat-error>
在组件中:
get foundingYear() {
return this.teamForm.get('foundingYear');
}
这取决于你的意图,
通常,对我来说,我对特定情况使用 hasError
,对一般情况使用 error
。
例如
<div *ngIf="foundingYear?.errors">
<mat-error *ngIf="foundingYear?.hasError('required')">Founding Year is required</mat-error>
<mat-error *ngIf="foundingYear?.hasError('limit')">Founding Year is not lower than 1999</mat-error>
</div>
替代我的日常代码
.html
<div *ngIf="foundingYear?.errors">
<mat-error *ngIf="hasError(foundingYear, 'required')">Founding Year is required</mat-error>
<mat-error *ngIf="hasError(foundingYear, 'limit')">Founding Year is not lower than 1999</mat-error>
<mat-error *ngIf="hasError(foundingYear, 'onlyNumber', 'notStartWithZero')">Got wrong format</mat-error>
</div>
.ts
isError(abControl: AbstractControl, ...error: string[]): boolean {
let isErr = false;
error.forEach((err) => {
isErr = isErr || abControl.errors?.[err];
});
return isErr;
}
希望对您有所帮助。
我在 Angular 中有反应形式。我在论坛上看到了这两种方法。有人说我们应该避免在模板中调用函数。那么有什么区别,哪个是最佳实践?
<mat-error *ngIf="foundingYear?.hasError('required')">Founding Year is required</mat-error>
<mat-error *ngIf="foundingYear?.errors?.['required']">Founding Year is required</mat-error>
在组件中:
get foundingYear() {
return this.teamForm.get('foundingYear');
}
这取决于你的意图,
通常,对我来说,我对特定情况使用 hasError
,对一般情况使用 error
。
例如
<div *ngIf="foundingYear?.errors">
<mat-error *ngIf="foundingYear?.hasError('required')">Founding Year is required</mat-error>
<mat-error *ngIf="foundingYear?.hasError('limit')">Founding Year is not lower than 1999</mat-error>
</div>
替代我的日常代码
.html
<div *ngIf="foundingYear?.errors">
<mat-error *ngIf="hasError(foundingYear, 'required')">Founding Year is required</mat-error>
<mat-error *ngIf="hasError(foundingYear, 'limit')">Founding Year is not lower than 1999</mat-error>
<mat-error *ngIf="hasError(foundingYear, 'onlyNumber', 'notStartWithZero')">Got wrong format</mat-error>
</div>
.ts
isError(abControl: AbstractControl, ...error: string[]): boolean {
let isErr = false;
error.forEach((err) => {
isErr = isErr || abControl.errors?.[err];
});
return isErr;
}
希望对您有所帮助。