html - @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
未定义。
谢谢。
解决方案
尝试
@ViewChild(ClrForm, {static: true}) clrForm;
从声明中删除'
(单引号)@ViewChild
更新(感谢@hippeelee)
import {ClrForm} from '@clr/angular';
推荐阅读
- json - 过滤数组代码不会呈现假定的过滤项Angular 9
- java - 用一千个“A”字符构建一个字符串
- entity-framework - EF中的跟踪行为范围
- ios - 当我无限滚动它们时,UICollectionViewCell 消失
- angular - 如何使用 AngularFireDatabase 和 Jasmine Spy/Mock 测试 Angular 服务
- c - calloc'd后无法修改C中的数组
- python - 在while循环外只执行一次代码
- python - 为什么我的 python 输入函数要求输入两次?
- reactjs - 如何在播放按钮后安排下一个按钮
- r - R Data Wrangling:混乱的限定符