如何从 angular 反应式表单元素的模板访问子组的有效 属性

How access valid property of subgroup from template of angular reactive form element

我正在尝试添加错误 class 当表单元素具有无效值但我无法访问它并且我不知道该怎么做时。

code.component.ts

this.dateRangeForm = this.fb.group({
      from: this.fb.group({
        fromYear: new FormControl(null, [ValidYearsValidator]),
        fromMonth: new FormControl(null, []),
        fromDay: new FormControl(null, [])
      }),
      to: this.fb.group({
        toYear: new FormControl(null, []),
        toMonth: new FormControl(null, []),
        toDay: new FormControl(null, [])
      })
    });

code.component.html

<form [formGroup]="dateRangeForm">
    <span formGroupName="from">
      <input type="text" [ngxOnlyNumbers]="true" maxlength="4" class="date-form-input" formControlName="fromYear"
        size="4" [class.error]="!fromYear.valid">

我的问题出在下面代码的最后输入处。我正在尝试访问 fromYear.valid 属性 但在加载表单后出现此错误:

错误类型错误:无法读取未定义的 属性 'valid'

您可以使用 dateGroupForm.controls.from.controls.fromYear 访问控件。

然后您可以使用 dateGroupForm.controls.from.controls.fromYear.value 访问该控件的属性(值、状态等)。

如果您想获取嵌套表单组中表单控件的状态,可以通过以下方式访问它:

  <input type="text" [ngxOnlyNumbers]="true" maxlength="4" class="date-form-input" formControlName="fromYear"
    size="4" [class.error]="!dateRangeForm.controls.from.controls.fromYear.valid">

dateRangeForm.controls.from.controls.fromYear.valid

您需要在您的组件中提供一个 get 方法来访问 fromYear 属性。

示例:

get fromYear(){
 return this.dateRangeForm.get('from.fromYear');
}