如何在Angular 6中构建具有多个组件的表单?

时间:2018-10-14 13:58:04

标签: angular typescript angular6 angular-reactive-forms angular-forms

我正在尝试构建跨多个组件的Reactive-Form

<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
   <app-names></app-names>
   <app-address></app-address>
   <app-phones></app-phones>
   <button type="submit">Submit</button>
</form>

当我尝试提交时,我得到了空的对象。

Stackblitz Here

2 个答案:

答案 0 :(得分:6)

进行以下更改

1。仅使用一个FormGroup,而不是为每个组件创建新的FormGroup

2。您有FormGroup的@Input,但是您没有作为输入传递。

3。从子组件中删除FormBuilder

app.component.html

<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
    <app-names [myForm]="myForm"></app-names>
    <app-address [myForm]="myForm"></app-address>
    <app-phones [myForm]="myForm"></app-phones>
    <button type="submit">Submit</button>
</form>

address.component.ts

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

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {

  @Input() myForm: FormGroup;
  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.myForm.addControl("homeAddress" , new FormControl());
    this.myForm.addControl("officeAddress" , new FormControl());
  }

}

对其他组件进行类似的更改。

答案 1 :(得分:0)

还有另一种方法可以不使用@Input

import { Component, OnInit } from '@angular/core';
import {
    FormControl,
    ControlContainer,
    FormGroupDirective
} from '@angular/forms';

@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.css'],
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
     }
  ]
})
export class AddressComponent implements OnInit {
  constructor(private parent: FormGroupDirective) {}

  ngOnInit() {
    const myForm = this.parent.form;
    myForm.addControl("homeAddress", new FormControl());
    myForm.addControl("officeAddress", new FormControl());
  }
}