在反应式表单控件中与 Validators.required 一起使用的自定义控件不显示指示器

问题描述 投票:0回答:1

假设我们有 2 个输入:MatInput 控件和自定义输入控件。

<div [formGroup]="form">
  <mat-form-field>
    <mat-label>Phone number</mat-label>
    <example-tel-input formControlName="tel"></example-tel-input>
    <mat-icon matSuffix>phone</mat-icon>
    <mat-hint>Include area code</mat-hint>
  </mat-form-field>
  <mat-form-field>
    <mat-label>Mobile number</mat-label>
    <input type="text" matInput formControlName="mobile" />
  </mat-form-field>
</div>

如果我们迫切需要这两个组件:

  form: FormGroup = new FormGroup({
    tel: new FormControl(null, [Validators.required]),
    mobile: new FormControl(null, [Validators.required]),
  });

手机显示指示符 (*),而电话则不显示。在文档中它说:

请注意,必需的属性仍然存在于模板中。 虽然对于验证来说不是必需的,但应该保留它 可访问性目的。

这意味着对于自定义组件,我需要在 HTML 模板中包含

required

<example-tel-input formControlName="tel" required></example-tel-input>

我想知道为什么会这样。

  1. 这是重复的代码。
  2. MatInput如何访问父类中需要的验证器而自定义控件却不能?

这是Stackblitz

angular validation angular-material angular-reactive-forms
1个回答
0
投票

在对 MatInput 进行一些帮助和调查之后,有人建议我能够通过

ngControl
访问验证器。 在自定义组件类构造函数中已经有:
@Optional() @Self() public ngControl: NgControl
那么不需要有默认的
_required
值(未定义):
private _required: boolean | undefined;

@Input()
  get required(): boolean {
    return (
      this._required ??
      this.ngControl?.control?.hasValidator(Validators.required) ??
      false
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.