Angular2结合了动态和嵌套形式

时间:2017-02-22 02:41:54

标签: angular nested-forms dynamic-forms

我在当前的应用开发中只使用动态表单。对于一个基础,我采用了Angular2示例:https://embed.plnkr.co/?show=preview。这是我无法弄清楚如何与嵌套动态生成的表单结合的部分:

// app/question-control.service.ts
import { Injectable }   from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { QuestionBase } from './question-base';

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: QuestionBase<any>[] ) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                              : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}

我将此示例用于嵌套表单库,但不幸的是此表单是静态生成的:http://plnkr.co/edit/Q5HYcpnPQosSYvk2KkoP?p=preview

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

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.html',
  directives: [REACTIVE_FORM_DIRECTIVES],
  providers:  []
})
export class AppComponent {
  form: FormGroup;
  myModel:any;

  constructor() {
    // initializing a model for the form to keep in sync with. 
    // usually you'd grab this from a backend API
    this.myModel = {
      name: "Joanna Jedrzejczyk",
      payOffs: [
        {amount: 111.11, date: "Jan 1, 2016", final: false},
        {amount: 222.22, date: "Jan 2, 2016", final: true}
      ]
    }

    // initialize form with empty FormArray for payOffs
    this.form = new FormGroup({
      name: new FormControl(''),
      payOffs: new FormArray([])
    });

    // now we manually use the model and push a FormGroup into the form's FormArray for each PayOff
    this.myModel.payOffs.forEach( 
      (po) => 
        this.form.controls.payOffs.push(this.createPayOffFormGroup(po))
    );

    // http://stackoverflow.com/questions/40453105/angular2-dynamic-form-calculate-amount-total/40453948#40454107
    this.form.controls.payOffs.valueChanges.subscribe((change) => {
      const calculateAmount = (payoffs: any[]): number => {
        return payoffs.reduce((acc, current) => {
           return acc + parseFloat(current.amount || 0);
        }, 0);
      }

      console.log(calculateAmount(this.form.controls.payOffs.value));
    });
  }

  createPayOffFormGroup(payOffObj) {
    console.log("payOffObj", payOffObj);
    return new FormGroup({
      amount: new FormControl(payOffObj.amount),
      date: new FormControl(payOffObj.date),
      final: new FormControl(payOffObj.final)
    });
  }

  addPayOff(event) {
    event.preventDefault(); // ensure this button doesn't try to submit the form
    var emptyPayOff = {amount: null, date: null, final: false};

    // add pay off to both the model and to form controls because I don't think Angular has any way to do this automagically yet
    this.myModel.payOffs.push(emptyPayOff);
    this.form.controls.payOffs.push(this.createPayOffFormGroup(emptyPayOff));
    console.log("Added New Pay Off", this.form.controls.payOffs)
  }

  deletePayOff(index:number) {
    // delete payoff from both the model and the FormArray
    this.myModel.payOffs.splice(index, 1);
    this.form.controls.payOffs.removeAt(index);
  }

  // calculate a sum of all payoffs
  sumPayOffs() {
    return this.myModel.payOffs.reduce((sum, val) => sum + val.amount, 0);
  }
}

我的问题是如何在动态表单中实现嵌套表单?我一直在尝试一些事情,但迄今为止没有任何工作。谢谢

0 个答案:

没有答案