首页 > 解决方案 > @ViewChild 在使用 Angular 表单时返回 undefined

问题描述

下面的表单(使用 Clarity Forms)是对话框的一部分:

<form clrForm
     clrLayout="horizontal"
     [formGroup]="editRecipientForm">
   <clr-input-container>
       <label>First Name</label>
       <input clrInput
              type="text"
              formControlName="firstName" />
       <clr-control-error>Field cannot be empty</clr-control-error>
   </clr-input-container>
   <clr-input-container>
       <label>Last Name</label>
       <input clrInput
              type="text"
              formControlName="lastName" />
       <clr-control-error>Field cannot be empty</clr-control-error>
   </clr-input-container>
</form>

在以下功能的帮助下打开:

onEditRecRow() {
    this.editRecipientForm = new FormGroup({
      ID: new FormControl({value: this.recSelectedList[0].ID, disabled: true}, Validators.required),
      firstName: new FormControl(this.recSelectedList[0].firstName, Validators.required),
      lastName: new FormControl(this.recSelectedList[0].lastName, Validators.required),
      emailID: new FormControl(this.recSelectedList[0].emailID, [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")])
    });

    this.editRecipientDialog = true
  }

如果任何表单控件无效,Clarity 可以帮助我提示错误消息。

我还希望在保存对话框中所做的所有更改后再次检查所有表单控件,我正在通过以下方式执行此操作:

  @ViewChild('ClrForm', {static: true}) clrForm;
  .
  .
  .
  onUpdateRecipient() {
    if (this.editRecipientForm.invalid) {
      this.clrForm.markAsTouched();
      console.log('Error There');
    } else {
      console.log('Recipient Updated');
    }    
  }

但是@ViewChild返回clrForm未定义。

谢谢。

标签: htmlangularangular-formsvmware-clarity

解决方案


尝试

@ViewChild(ClrForm, {static: true}) clrForm;

从声明中删除'(单引号)@ViewChild

更新(感谢@hippeelee)

import {ClrForm} from '@clr/angular';


推荐阅读