簡體   English   中英

在 ReactiveForm 中設置 Angular 2 FormArray 值?

[英]Setting Angular 2 FormArray value in ReactiveForm?

這里已經有一個類似的問題( 設置初始值 Angular 2 反應式表單數組),但我對答案不滿意,或者可能正在尋找其他解決方案。

我認為擁有 FormArray 的重點是傳遞對象數組,它應該創建相同數量的組件。 但是在上面的示例中,如果您查看提供的 plunker ,即使在提供了兩個 Addresses 對象之后,也會創建一個 Address ,因為它的空白版本已經在 ngOnInit() 中創建。

所以我的問題是,如果在 ngOnInit() 我有這樣的地址: this._fb.array([]) // 空白列表,那么我應該如何設置它的值,它從 N 個地址動態創建 N 個地址在我的 TypeScript 數組中?

要從表單數組中設置和刪除值,請參閱以下代碼。 給定的代碼僅供您參考,請根據您的代碼進行相應調整。

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

我有相同的問題。 這是我如何做到的:

正如您所提到的,您像這樣初始化表單數組:

  addresses: this._fb.array([])

然后在 ngOnInit() (或在我的情況下 ionViewDidLoad() - 使用 Ionic 2)中,您執行異步操作以訪問遠程數據庫並通過承諾或可觀察(並訂閱可觀察)取回值。 然后將所有其他非 formArray 的表單控件 patchValue (如果您有表單組和表單數組,請不要使用 setValue !!)。

對於 formArray,請執行以下操作:

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

其中 data.addresses 是一個地址數組(您在之前的操作中從相同的形式創建它們。)

希望這能解決您和我的問題:) FormArray 功能強大,希望有更多資源來教我們如何正確使用它。

這是一個工作代碼。 您可以將其插入到項目中並進行測試。

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