web-dev-qa-db-ja.com

子コンポーネント内でformGroupNameを使用する方法

子コンポーネント内でformGroupNameを使用するにはどうすればよいですか?例えば:

私はParentFormComponentを持っています

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


 this.parentForm = this.fb.group({
        _general: this.fb.group ({
           ProjectName:''
       })
  })
 }

HTMLで:

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

それは素晴らしい仕事ですが、子コンポーネントを使用したいときはうまくいきません:

<form [formGroup]="parentForm" (ngSubmit)="submitForm()">
          <app-child [parentForm]='parentForm'></app-child>
      </form> 

子コンポーネントに挿入すると:

<div formGroupName="_general">
            <mat-form-field>
                 <input matInput placeholder="Project name" 
                 formControlName="ProjectName">
            </mat-form-field>
        </div> 

tsファイル内

 @Input() parentForm:FormGroup;

エラーが発生しました:formGroupNameは親のformGroupディレクティブと一緒に使用する必要があります。formGroupディレクティブを追加して、既存のFormGroupインスタンスに渡します(クラスで作成できます)。

7
Livnat Menashe

入力プロパティバインディングを使用する代わりにFormGroupDirectiveを使用

FormGroupDirective

このディレクティブは、既存のFormGroupインスタンスを受け入れます。次に、このFormGroupインスタンスを使用して、子のFormControl、FormGroup、およびFormArrayインスタンスを子のFormControlName、FormGroupName、およびFormArrayNameディレクティブに一致させます。

Viewprovidersを使用してcontrolContainerを提供し、子コンポーネントにFormGroupDirectiveを挿入して、親フォームのインスタンスを取得します。

app.parent.html

<form [formGroup]="parentForm">
  <app-child></app-child>
</form>

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

  }
}

child.component.html

<div formGroupName="_general">
     <mat-form-field>
                 <input matInput placeholder="Project name" 
                 formControlName="ProjectName"> 
      <mat-form-field>  
 </div>

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

11
Chellappan