【发布时间】:2021-10-09 11:00:40
【问题描述】:
我正在尝试根据遇到的验证器类型显示 mat 错误。需要一个验证器(如果字段被触摸并留空,将显示)和另一个 maxLength(如果字段已被触摸并且输入超过 20 个字符,将显示) - 每个场景都应显示不同的 mat 错误消息。
首先,我有自己的表单组(在 component.ts 中),带有表单控件及其各自的验证器:
this.addBranchDetailsForm = this.fb.group({
branchName: ['', Validators.required, Validators.maxLength(20)]
});
其次,在 component.html 文件中,我有 Mat 表单字段,它引用了上述表单组和控件:
<form [formGroup]="addBranchDetailsForm">
<mat-form-field hintLabel="Enter the new branch name">
<mat-label>Branch Name</mat-label>
<input matInput #input maxlength="30" formControlName="branchName">
<mat-hint align="end">{{input.value?.length || 0}}/30</mat-hint>
<mat-error *ngIf="branchName">{{formOneErrorMessage()}}</mat-error>
</mat-form-field>
</form>
最后,我的 component.ts 文件中有“formOneErrorMessage”方法,它负责条件错误处理:
formOneErrorMessage() {
if (this.addBranchDetailsForm.get('branchName')?.hasError('required')) {
return 'Enter new branch name';
}
else if (this.addBranchDetailsForm.get('branchName')?.hasError('maxLength')) {
return 'The new branch name may not be more then 20 characters';
}
}
我遇到的问题如下:
在 component.html 文件中,关于 mat 错误的 ngIf 中对“branchName”的引用,它显示“Property 'branchName' does not exist on type 'CreateBranchComponent'.ngtsc(2339)” .
同样,参考 mat 错误本身中的“formOneErrorMessage()”方法,它说“属性 'formOneErrorMessage' 在类型 'CreateBranchComponent'.ngtsc(2339) 上不存在”。
最后。查看 component.ts 文件中的“formOneErrorMessage()”方法,返回也抛出错误,说明:“类型 'string' 不可分配给类型 'void'.ts(2322):”...
我的怀疑是我没有在“formOneErrorMessage()”方法中正确引用 branchName 表单控件。虽然,否则我很不确定。
【问题讨论】:
标签: html angular typescript validation angular-material