【发布时间】:2019-01-15 08:09:04
【问题描述】:
如您所知,当我们在 Angular 中使用响应式表单创建表单时,我们将 formcontrolname 分配给元素,并手动创建如下所示的表单控件:
<form [formGroup]="ntForm" (change)="onChange($event)" (ngSubmit)="onSubmit()" class="nt-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="User Id" formControlName="userId" [min]="5">
<mat-error >{{getErrors('userId')}}</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<input matInput placeholder="Id" formControlName="id" required [min]="10">
<mat-error >{{getErrors('id')}}</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<input matInput placeholder="Title" formControlName="title" [email]="true">
<mat-error >{{getErrors('title')}}</mat-error>
</mat-form-field>
<button class="nt-form-button" type="submit">Submit</button>
手动添加表单控件:
this.ntForm = this.form.group({
'id': new FormControl('id'),
'userId': new FormControl('userId'),
'title': new FormControl('title')
});
一开始这似乎很简单,但如果我们有 20 个元素呢? 我们需要手动添加名称并维护它们。在敏捷开发中,这将是痛苦的。 为了解决这个问题,我创建了一个基于 formControlName 属性自动创建控件的函数:
fillControls(data) {
const els: any = document.getElementsByClassName('nt-form')[0]
.querySelectorAll('[formControlName]');
els.forEach(node => {
const controlName = node.attributes['formcontrolname'].nodeValue;
this.ntForm.addControl(controlName, new FormControl('', []));
});
}
但是使用这种方法会发出错误说明('找不到具有名称的控件:''),因为我首先使用空控件初始化表单并填充它。 我怎么解决这个问题?谢谢
【问题讨论】:
-
你为什么在角度使用 document.getElementsByClassName
-
因为我只想查询指定类的表单元素。
-
在角度你可以使用元素参考选择元素
-
是的,代码可以稍后优化,但现在需要解决当前的问题。
-
你想用动态数据创建表单吗?
标签: angular angular-reactive-forms angular-forms