在父组件中创建FormGroup时,需要同时传递子组件中的FormControl对象作为参数,并通过@Input()装饰器将FormGroup和FormControl对象传递给子组件。然后在子组件中,使用[formControl]="control"来绑定FormControl对象和模板中的表单控件,确保子属性输入表单能够正确绑定到FormGroup。
以下是代码示例:
父组件:
export class ParentComponent implements OnInit {
formGroup: FormGroup;
control = new FormControl('');
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.formGroup = this.fb.group({
name: '',
child: this.control
});
}
}
父组件模板:
子组件:
export class ChildComponent implements OnInit {
@Input() formGroup: FormGroup;
@Input() control: FormControl;
constructor() {}
ngOnInit() {}
}
子组件模板: