简体   繁体   English

@ViewChild在使用Angular Forms时返回未定义

[英]@ViewChild returns undefined while using Angular Forms

Below form(using Clarity Forms) is a part of a dialog: 表单下方(使用清晰表单)是对话框的一部分:

<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>

which opens with the help of the following function: 在以下功能的帮助下打开:

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 helps me to prompt error messages if any Form Control is invalid. 如果有任何Form Control无效,那么清晰度可以帮助我提示错误消息。

I also wanted all Form Controls to be checked again once I save all my changes made in dialog, which I am doing in the following way: 我还希望在保存所有在对话框中所做的更改后再次检查所有窗体控件,这是通过以下方式进行的:

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

But @ViewChild is returning clrForm as undefined. 但是@ViewChild返回的clrForm为未定义。

Thanks. 谢谢。

Try 尝试

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

remove ' (single quotes) from the statement of @ViewChild @ViewChild的语句中删除' (单引号)

Update (Thanks to @hippeelee) 更新(感谢@hippeelee)

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

Could it be you're not referencing clrForm properly on your template? 可能是您在模板上没有正确引用clrForm吗?

Try <form #ClrForm clrLayout="horizontal" [formGroup]="editRecipientForm"> <clr-input-container> 尝试<form #ClrForm clrLayout="horizontal" [formGroup]="editRecipientForm"> <clr-input-container>

https://angular.io/api/core/ViewChild https://angular.io/api/core/ViewChild

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM