【问题标题】:Setting Angular 2 FormArray value in ReactiveForm?以反应形式设置 Angular 2 FormArray 值?
【发布时间】:2017-06-03 06:42:54
【问题描述】:

这里已经有一个类似的问题(Setting initial value Angular 2 reactive formarray),但我对答案不满意,或者可能正在寻找其他解决方案。

我认为拥有 FormArray 的重点是传递对象数组,它应该创建相同数量的组件。但是在上面的示例中,如果您查看提供的 plunker ,即使在提供了两个 Addresses 对象之后,也创建了一个 Address ,因为它的空白版本已经在 ngOnInit() 中创建。

所以我的问题是,如果在 ngOnInit() 我有这样的地址: this._fb.array([]) // 空白列表, 那么我应该如何设置它的值,让它从我的 TypeScript 数组中的 N 个地址动态创建 N 个地址?

【问题讨论】:

  • 有什么帮助吗?目前首先我必须在 fb.array 中添加空白地址,然后需要绑定模型数组。而我希望它简单地将数组绑定到 fb.array 并期望生成 n 个地址。
  • 嗨丹尼,看看我的回答。我用它来解决它。

标签: javascript angular forms angular-reactive-forms reactive-forms


【解决方案1】:

我也有同样的问题。这是我的做法:

正如你所提到的,你像这样初始化你的表单数组:

  addresses: this._fb.array([])

然后在 ngOnInit() 内部(或者在我的情况下是 ionViewDidLoad() - 使用 Ionic 2),您执行异步操作以访问远程数据库并通过 promise 或 observable 取回值(并订阅 observable)。然后你将patchValue 应用于不是formArray 的所有其他表单控件(如果你有表单组和表单数组,请不要使用setValue !!)。

对于formArray,这样做:

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

其中 data.addresses 是一个地址数组(您在之前的操作中使用相同的表单创建它们。)

希望这能解决您和我的问题 :) FormArray 功能强大,希望有更多资源来教我们如何正确使用它。

【讨论】:

  • this.yourForm.setControl('addresses', this.fb.array(data.addresses || [])); 对我来说效果很好!
  • 谢谢,这行得通!就我而言,我试图用 patchValue 从 FormArray 中删除项目,但它没有用。但是,如果我们使用具有不同序列的相同项目(角度版本 - 10.1.0),patchValue 确实有效
【解决方案2】:

要设置和删除 表单数组 中的值,请参阅以下代码。给出的代码仅供参考,请根据您的代码进行相应调整。

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);        
    }
}

【讨论】:

    【解决方案3】:

    这是一个有效的代码。您可以将其插入到项目中并进行测试。

    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 || []));
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 2022-01-15
      • 2018-06-05
      • 1970-01-01
      • 2021-09-16
      • 2019-10-30
      • 2020-11-07
      • 2018-01-29
      • 2019-07-07
      相关资源
      最近更新 更多