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

Sha*_*hdi 2 typescript angular angular-reactive-forms angular-forms angular6

我正在尝试构建跨越多个组件的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>
Run Code Online (Sandbox Code Playgroud)

当我尝试提交时,我得到空对象.

Stackblitz在这里

Sun*_*ngh 8

进行以下更改

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

你有@Input FormGroup但是你没有作为输入传递.

3. @Input从子组件中删除.

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>
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

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


kat*_*des 8

还有另一种选择可以不使用@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());
  }
}
Run Code Online (Sandbox Code Playgroud)