如何在子组件中使用formGroupName

Liv*_*she 6 angular angular-reactive-forms angular6

如何在子组件中使用formGroupName?例如:

我有ParentFormComponent

    parentForm: FormGroup;
    constructor(private fb: FormBuilder, private http: Http) { }
    ngOnInit() {


 this.parentForm = this.fb.group({
        _general: this.fb.group ({
           ProjectName:''
       })
  })
 }
Run Code Online (Sandbox Code Playgroud)

在html中:

  <form [formGroup]="parentForm" (ngSubmit)="submitForm()">
     <div formGroupName="_general">
        <mat-form-field>
             <input matInput placeholder="Project name" 
             formControlName="ProjectName">
        </mat-form-field>
    </div> 
  </form> 
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但是当我想使用子组件时,它不起作用:

<form [formGroup]="parentForm" (ngSubmit)="submitForm()">
          <app-child [parentForm]='parentForm'></app-child>
      </form> 
Run Code Online (Sandbox Code Playgroud)

当我将其插入子组件时:

<div formGroupName="_general">
            <mat-form-field>
                 <input matInput placeholder="Project name" 
                 formControlName="ProjectName">
            </mat-form-field>
        </div> 
Run Code Online (Sandbox Code Playgroud)

并在ts文件中

 @Input() parentForm:FormGroup;
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:formGroupName必须与父formGroup指令一起使用。您需要添加一个formGroup指令,并将其传递给现有的FormGroup实例(您可以在类中创建一个)。

Che*_*pan 11

代替使用输入属性绑定,使用FormGroupDirective

FormGroupDirective

该指令接受现有的FormGroup实例。然后,它将使用此FormGroup实例将任何子FormControl,FormGroup和FormArray实例与子FormControlName,FormGroupName和FormArrayName指令匹配。

使用Viewproviders提供controlContainer,在子组件中注入FormGroupDirective以获取父窗体实例

app.parent.html

<form [formGroup]="parentForm">
  <app-child></app-child>
</form>
Run Code Online (Sandbox Code Playgroud)

child.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, ControlContainer, FormGroupDirective, Validators, FormBuilder, NgModel } from '@angular/forms';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ChildComponent implements OnInit {
  childForm;
  constructor(private parentF: FormGroupDirective) { }

  ngOnInit() {

    this.childForm = this.parentF.form;
    this.childForm.addControl('_general', new FormGroup({
      ProjectName: new FormControl('')
    }))

  }
}
Run Code Online (Sandbox Code Playgroud)

child.component.html

<div formGroupName="_general">
     <mat-form-field>
                 <input matInput placeholder="Project name" 
                 formControlName="ProjectName"> 
      <mat-form-field>  
 </div>
Run Code Online (Sandbox Code Playgroud)

示例:https//stackblitz.com/edit/angular-ezqupz