【问题标题】:Used formarray without form tag in html content, so added formtag and code does not work在html内容中使用了没有form标签的formarray,所以添加了formtag和代码不起作用
【发布时间】:2020-09-14 06:31:43
【问题描述】:

Angular 9:在 html 内容中使用了没有表单标签的 formarray,但现在需要向 html 组件添加验证和添加表单标签,现在代码不起作用!

使用formarray在按钮点击时动态生成一行控件(textbox和textarea);html组件没有form标签,这是通过首先创建一个formarray来实现的:

requirement=new FormArray([]);

并在 html 组件中添加以下内容:

    <tr let req of requirement.controls let i=index>
<td>
<input type="number" name="Req#" [(NgModel)]="reqno"/>
</td>
<td>
<textarea type="text" name="Req" [(NgModel)]="req"></textarea>
</td>
:
:
:
</tr>

在按钮单击时应用以下代码:

this.requirement.push(new FormControl(''));

这有助于生成动态控件,但无法执行验证,因此将表单标签添加到 html 组件并添加 formControlName 而不是 NgModel 和上面的打字稿代码: 声明formarray如下:

公开要求:FormArray;

并在 ngOnInit() 上进行相同的初始化:

this.requirement=new FormArray([
new FormGroup({

reqno:new FormControl('');
req:new FormControl('');

})
]);

更改后,Ngif 和 NgFor 不起作用。谁能帮忙。

【问题讨论】:

  • 你得到什么错误信息?
  • @lynx 242 : 错误:formControlName 必须与 FormGroup 指令一起使用。您需要添加一个 FormGroup 指令并将现有的 FormGroup 实例传递给它 - 这是从控制台获得的。跨度>

标签: html angular typescript


【解决方案1】:

@AleshaDeveloper,FormArray 是 ReactiveForms,[(ngModel)] 是模板驱动的表单

好吧,创建一个返回 formGroup 的函数。您可以在函数中使用验证器

newFormGroup()
{
  return new FormGroup({
    reqno:new FormControl(''),
    req:new FormControl('',Validators.required)
  })
}

并使用它,在 ngOnInit 中创建表单并在函数中添加元素

ngOnInit()
{
    this.requirement=new FormArray([this.newFormGroup()])
}

addGroup()
{
   this.requirement.push(this.newFormGroup())
}

我们创建一个辅助函数,它在 index(*) 处返回 formArray 的 formGroup

  groupAt(index)
  {
    return this.requirement.at(index) as FormGroup
  }

现在,我们可以使用这个函数为每一行创建一个formGroup

<tr *ngFor="let group of requirement.controls;let i=index" [formGroup]="groupAt(i)">
<td>
  <input type="number" formControlName="reqno"/>
</td>
<td>
  <textarea type="text" name="Req" formControlName="req"></textarea>
</td>
</tr>

看到你像使用另一个 formGroup 一样使用 formControlName,参见 docs

你可以在stackblitz看到

(*) 在 Angular 之前,你可以直接写 [formGroup]="group",但在最近的 Angular 中,你需要帮助 Angular 并说这是一个 FormGroup

【讨论】:

  • 我需要在按钮点击时获得这些控件。
  • formarray 的值为this.requirement.value,查看文档:angular.io/guide/forms-overview
  • 会试试这个,让你知道 Eliseo。
  • 还有一个问题;除了这些控件之外,此 html 组件中还有许多其他输入框和选择框;所以我是否也应该指定这些框来创建表单数组...不对!
  • 嗨,Eliseo,试过这个,但代码仍然不起作用;你有teamweaver吗?
猜你喜欢
  • 1970-01-01
  • 2013-05-08
  • 2020-05-08
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多