条件 Angular Material 错误消息不起作用?

Conditional Angular Material Error Message not working?

我正在尝试根据遇到的验证器类型显示垫错误。需要一个验证器(如果字段被触摸并留空,将显示)和另一个 maxLength(如果字段被触摸且输入超过 20 个字符,将显示)- 每个场景应显示不同的垫错误消息。

首先,我有自己的表单组(在 component.ts 中),带有表单控件及其各自的验证器:

this.addBranchDetailsForm = this.fb.group({
     branchName: ['', Validators.required, Validators.maxLength(20)]
});

其次,在 component.html 文件中,我有引用上述表单组和控件的 Mat Form Field:

<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”的引用,它说“属性 'branchName' 不存在于输入 'CreateBranchComponent'.ngtsc(2339)".

同样,参考 mat 错误本身中的“formOneErrorMessage()”方法,它说“属性 'formOneErrorMessage' 在类型 'CreateBranchComponent'.ngtsc(第2339章).

最后。查看 component.ts 文件中的“formOneErrorMessage()”方法,returns 也抛出错误,指出:“类型 'string' 不可分配给类型 'void'。 ts(2322):"...

我怀疑我没有在“formOneErrorMessage()”方法中正确引用 branchName 表单控件。尽管如此,否则我不太确定。

我最终使用了以下内容(在 component.ts 中):

public errorHandling = (control: string, error: string) => {
    return this.addBranchDetailsForm.controls[control].hasError(error);
  }

然后在component.html内:

<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="errorHandling('branchName','required')">
                  Branch Name may not be empty
                </mat-error>
                <mat-error *ngIf="errorHandling('branchName','maxlength')">
                  Branch Name may not be more than 20 characters
                </mat-error>
              </mat-form-field>