如何将formGroup添加到另一个formGroup

时间:2017-01-07 04:36:56

标签: angular typescript angular2-forms

我找到了这个答案,它显示了如何将表单控件添加到父表单中:

Reuse components in angular2 model driven forms

但我希望能够像这样将新的formGroups添加到页面的不同区域。

<form [formGroup]="myForm">
  <!--... other inputs -->
  <md-tab-group formGroupName="nutrition">
    <md-tab formGroupName="calories">
      <template md-stretch-tabs="always" md-tab-label>Calories</template>
      <template md-tab-content>
        <calories></calories> <!-- I want to add controll groups like this-->
      </template>
    </md-tab>
    <md-tab formGroupName="carbs">
      <template md-stretch-tabs="always" md-tab-label>Carbs</template>
      <template md-tab-content>
        <carbs></carbs>
      </template>
    </md-tab>
  </md-tab-group>
</form>

整个表单模型应如下所示:

{
   name: '',
   nutrition:{
      calories: {
        total: ''
        // more
      },
      carbs: {
        total: ''
        // more
      }
}

我已经能够像这样添加nutrition formGroup:

<nutrition [parentForm]="myForm"></nutrition>

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

@Component({
  selector: 'nutrition',
  template: `
  <div [formGroup]="parentForm"></div>
  `
})
export class NutritionComponent implements OnInit {

    @Input() parentForm: FormGroup;

    nutritionGroup: FormGroup;

    constructor(private _fb: FormBuilder) {
    }

    ngOnInit() {
      this.nutritionGroup = new FormGroup({
        blank: new FormControl('', Validators.required)
      });
      this.parentForm.addControl('nutrition', this.nutritionGroup);
    }
}

但我无法弄清楚如何将nutrition表单组传递给calories formGroup,如下所示:

<calories [parentControl]="nutrition"></calories>

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

@Component({
  selector: 'calories',
  template: ``
})
export class CaloriesComponent implements OnInit {

  @Input() parentControl: FormGroup;
  caloriesForm: FormGroup;

  constructor(private _fb: FormBuilder) {  }
  ngOnInit(){
    this.caloriesForm = new FormGroup({
        blank: new FormControl('', Validators.required)
      });

    this.parentControl.addControl('calories', this.caloriesForm);
  }
}

可以这样做吗?

1 个答案:

答案 0 :(得分:4)

如果您(或任何人)仍然感兴趣,将控件添加到external-dns.alpha.kubernetes.io/hostname: nginx.external-dns-test.my-org.com.后,您需要将其发送回父组件,以便更新。

parentControl

在父html元素上,您需要将其重新签名回import { Output, EventEmitter } from '@angular/core'; @Output() onFormGroupChange: EventEmitter<FormGroup> = new EventEmitter<FormGroup>(); this.parentControl.addControl('calories', this.caloriesForm); this.onFormGroupChange.emit(this.parentControl); parentControl

你的方法

(onFormGroupChange)="setParentControl($event)"

然后,您将在FormGroup public setParentControl(formGroup: FormGroup) { this.myForm = formGroup; } 中拥有控件并在您的父元素上执行任何操作: myForm

Haven不包含所有代码,只包含您需要的代码:)