【问题标题】:How to build form with multiple components in Angular 6?如何在 Angular 6 中构建具有多个组件的表单?
【发布时间】:2019-03-19 02:15:38
【问题描述】:

我正在尝试构建跨越多个组件的 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

【问题讨论】:

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


    【解决方案1】:

    进行以下更改

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

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

    【讨论】:

      【解决方案2】:

      还有另一种不使用@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());
        }
      }
      

      【讨论】:

      • 感谢一百万伙计,我从未见过这种方式,我发现它如此简单和干净!
      猜你喜欢
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多