如何在子组件中使用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实例(您可以在类中创建一个)。
答案 0 :(得分:8)
使用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>