简体   繁体   English

在 ReactiveForm 中设置 Angular 2 FormArray 值?

[英]Setting Angular 2 FormArray value in ReactiveForm?

There is already a similar question here ( Setting initial value Angular 2 reactive formarray ) but I am not satisfied with the answer or maybe looking for some other solution.这里已经有一个类似的问题( 设置初始值 Angular 2 反应式表单数组),但我对答案不满意,或者可能正在寻找其他解决方案。

I think whole point of having FormArray is to pass the array of objects and it should create equal number of components.我认为拥有 FormArray 的重点是传递对象数组,它应该创建相同数量的组件。 But in this above example if you look at the provided plunker , even after providing two Addresses object one Address was created because its blank version was already created in ngOnInit() .但是在上面的示例中,如果您查看提供的 plunker ,即使在提供了两个 Addresses 对象之后,也会创建一个 Address ,因为它的空白版本已经在 ngOnInit() 中创建。

So my question is if in ngOnInit() I have it like this addresses: this._fb.array([]) // blank list, then how should I set its value that it dynamically creates N number of addresses from N number of addresses in my TypeScript array ?所以我的问题是,如果在 ngOnInit() 我有这样的地址: this._fb.array([]) // 空白列表,那么我应该如何设置它的值,它从 N 个地址动态创建 N 个地址在我的 TypeScript 数组中?

To set and remove the values from the form array refer to the below code.要从表单数组中设置和删除值,请参阅以下代码。 The given code is just for your reference, please adjust to your code accordingly.给定的代码仅供您参考,请根据您的代码进行相应调整。

import { FormArray, FormBuilder, FormGroup} from '@angular/forms';

export class SomeComponent implements OnInit {

consutructor(public  fb:FormBuilder) { }

    ngOnInit() {
      public settingsForm: FormGroup = this.fb.group({
          collaborators:this.fb.array([this.buildCollaboratorsGroup(this.fb)])
      });     

      this.setFormArrayValue();
   }

    public buildCollaboratorsGroup(fb:FormBuilder): FormGroup {
        return fb.group({
                           email:'',
                           role:''
                       });
    }


    // Here I'm setting only one value if it's multiple use foreach        
    public setFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
        controlArray.controls[0].get('email').setValue('yourEmailId@gmail.com');
        controlArray.controls[0].get('role').setValue(2);
    }

    // Here removing only one value if it's multiple use foreach        
    public removeFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
        controlArray.removeAt(0);        
    }
}

I am having the same issue.我有相同的问题。 Here is how I do it:这是我如何做到的:

As you mentioned, you initialize your form Array like this:正如您所提到的,您像这样初始化表单数组:

  addresses: this._fb.array([])

Then inside ngOnInit() (or in my case ionViewDidLoad() - using Ionic 2), you do your async operation to hit your remote database and get back the value either via promise or observable (and subscribe to the observable).然后在 ngOnInit() (或在我的情况下 ionViewDidLoad() - 使用 Ionic 2)中,您执行异步操作以访问远程数据库并通过承诺或可观察(并订阅可观察)取回值。 Then you patchValue to all the other form control that is NOT formArray (don't use setValue if you have form group and form array!!).然后将所有其他非 formArray 的表单控件 patchValue (如果您有表单组和表单数组,请不要使用 setValue !!)。

For the formArray, do this:对于 formArray,请执行以下操作:

   this.yourForm.setControl('addresses', this.fb.array(data.addresses || []));

Where data.addresses is an array of addresses (you create them from the same form on previous operation.)其中 data.addresses 是一个地址数组(您在之前的操作中从相同的形式创建它们。)

Hope this solve your question as well as mine :) FormArray is powerful, wish there is more resources to teach us how to use it correctly.希望这能解决您和我的问题:) FormArray 功能强大,希望有更多资源来教我们如何正确使用它。

This is a working code.这是一个工作代码。 You can insert it into the project and test it.您可以将其插入到项目中并进行测试。

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private addresses: string[] = ['Address 1', 'Address 2', 'Address 3'];
  private form: FormGroup;

  constructor(private formBuilder: FormBuilder){}

  ngOnInit(){
    // Init Form
    this.form = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null, [Validators.required]),
        'email': new FormControl(null, [Validators.required, Validators.email])
      }),
      'addresses': new FormArray([])
    });

    // If you want to insert static data in the form. You can use this block.
    this.form.setValue({
      'userData': {
        'username': 'Vic',
        'email': 'email@email.com'
      },
      'addresses': [] // But the address array must be empty.
    });

    // And if you need to insert into the form a lot of addresses. 
    // For example, which belong to one user and so on. 
    // You must use this block. 
    // Go through the array with addresses and insert them into the form.
    this.addresses.forEach((value) => {
      const control = new FormControl(value, Validators.required);
      (<FormArray>this.form.get('addresses')).push(control);
    });
    // Or you can use more better approach. But don't forget to initialize FormBuilder.
    this.form.setControl('addresses', this.formBuilder.array(this.addresses || []));

  }
}

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

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