Angular 2:无法在反应表单中添加表单组以形成数组

时间:2017-01-07 03:06:15

标签: javascript angular

我正在构建动态表单,并希望动态添加表单组。

这是我的代码几乎可以运作:

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

export class CombinedComponent implements OnInit {

    ltsForm: FormGroup;

    constructor(private formBuilder: FormBuilder) {
    }

    ngOnInit() {
        this.ltsForm = this.initFormGroup();

        // init products
        for (let i = 0; i < 3; i++) { // add dynamically products
            this.addProduct();
        }

        console.log(this.ltsForm); // Array 'prods' is empty
    }

    // initialize form group, but don't add products yet because they will be added dynamically later
    initFormGroup() {
        let group = this.formBuilder.group({
            products: this.initProductGroup()
        });

        return group;
    }

    initProductGroup() {
        let group = this.formBuilder.group(
            {
                //initialize empty formbuilder array
                prods: this.formBuilder.array([])
            }
        );

        return group;
    }

    initProducts() {
        return this.formBuilder.group({
            id: [''],
            value: false, // checkbox value
        });
    }

    addProduct() {
        <FormArray>this.ltsForm.controls['products'].value.prods.push(this.initProducts());

        console.log(this.ltsForm); // Array 'prods' contains 3 FormGroup elements
    }
} 

模板:

<form [formGroup]="ltsForm"
      novalidate
      (ngSubmit)="save(ltsForm)">

    <div formGroupName="products">
        <div formArrayName="prods">

            <div *ngFor="let product of ltsForm.controls.products.value.prods.controls; let i = index">
                <div [formGroupName]="i">
                    <input type="checkbox"
                           formControlName="value"
                           id="product_{{ i }}"
                           name="product_{{ i }}">
                </div>
            </div>

        </div>
    </div>

    <button type="submit"
            [disabled]="!ltsForm.valid">
        Submit
    </button>
</form>

在方法addProduct()中,我将整个FormGroup元素推送到'prods'数组。所以最后ngOnInit()中控制台的输出只包含一个空的'prods'数组,而addProduct()方法中控制台输出的数组包含3个元素。它看起来像this.ltsForm失去了它的引用,并没有更新。有什么想法吗?

UPD:刚刚发现,如果我从模板中删除整个内容,我就会得到充满数据的“prods”。

1 个答案:

答案 0 :(得分:16)

有一些小错误和复杂性,所以我减少了你的例子,并将其重建。 Angular团队提供了nested form arraynested form group的示例,这些示例非常有用。这是流程(和plnkr):

  1. 有一个简单小组正在工作:class obj { public string name {get ; set; } public string pic_large {get ; set; } public id {get ; set; } } using System.Web.Script.Serialization; . . var obj = new JavaScriptSerializer().Deserialize<obj>(jsonString);
  2. 有一个组,其中包含一系列控件 UIGraphicsBeginImageContextWithOptions(self.drawSignView.bounds.size, NO, [UIScreen mainScreen].scale); [self.drawSignView drawViewHierarchyInRect:self.drawSignView.bounds afterScreenUpdates:YES]; UIImage *signImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(signImage) { //Get Image from sign view Succesfully } else { UIAlertView *alertviewshow =[[UIAlertView alloc] initWithTitle:@"Warning!" message:@"Please Sign" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alertviewshow show]; } 。我跳过{ projects: '' },似乎没必要。

    { projects: ['a', 'b', 'c'] }
  3. 最后一步替换数组中的控件

    prods