本文介绍了反应性表单:如何在以后的某个时间点在Angular 7/8/9中将新的FormGroup或FormArray添加到现有的FormGroup中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在StackOverflow的其他示例中,有很多关于在FormArrays中使用FormGroups的问题.但是我的问题恰恰相反.

In the other examples at StackOverflow there are many questions about using FormGroups in FormArrays. But my question is the opposite.

FormArrays具有push方法,这使很多事情成为可能. FormGroups确实具有用于添加简单FormControl的addControl方法. Afaik FormGroups没有addFormArray or addFormGroup方法.因此,我需要您的帮助.

FormArrays have a push method, that makes many things possible. FormGroups have indeed an addControl method for adding simple FormControls. Afaik FormGroups do not have addFormArray or addFormGroup method. Therefore I need your help.

以下情况:

this.myForm = this.fb.group({
  id: this.fb.control([this.book.id]),
  // or short form `id: [this.book.id],`
});

在稍后的时间点添加简单的控件很容易:

Adding a simple control at a later point in time is easy:

this.myForm.addControl('isbn', this.fb.control(this.book.isbn));

但是如何将FormArrays和FormGroups添加到现有FormGroup中呢?例如,我想为此使用以下数组和对象:

But what about adding FormArrays and FormGroups into an existing FormGroup? For instance, I would like to use the following array and object for this purpose:

const authors  = ['George Michael', 'Aretha Franklin'];
const metaData = { description : 'Great Book', publication: 2019}

仅当它们存在时,我才想添加authorsArray或metaData.这就是原因,为什么我以后要添加它们.

I would like to add authorsArray or metaData only then if they are existing. That's the reason, why I want to add them at a later time.

p.s.请忽略验证规则.

p.s. Please ignore the validation rules.

推荐答案

FormGroup addControl 方法接受AbstractControl作为参数,该参数可以是FormControlFormArray或另一个FormGroup,因为它们都扩展了AbstractControl.

FormGroup addControl method accepts AbstractControl as parameter which can be either a FormControl or a FormArray or another FormGroup as they all extend AbstractControl.

class FormGroup extends AbstractControl
...
class FormControl extends AbstractControl
...
class FormArray extends AbstractControl

FormBuilder 可以帮助您使用array()group()方法构建此类控件:

FormBuilder can help you building such controls with array() and group() methods:

this.myForm = this.fb.group({
  id: this.fb.control([this.book.id]),
  authors: this.fb.array(['George Michael', 'Aretha Franklin']),
  metaData: this.fb.group({ description : 'Great Book', publication: 2019})
});

之后,您仍然可以使用工厂来构建所需的控件(无论它是哪种控件):

You still can use the factory afterwards to build the controls you need (no matter what kind of control it is):

this.myForm.addControl('authors', this.fb.array(['George Michael', 'Aretha Franklin']))
this.myForm.addControl('metaData', this.fb.group({ description : 'Great Book', publication: 2019}))

这篇关于反应性表单:如何在以后的某个时间点在Angular 7/8/9中将新的FormGroup或FormArray添加到现有的FormGroup中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:45