问题描述
我正在处理大表单,所以我计划将表单截断为多个子组件,这有助于轻松集成和维护.使用表单构建器,我正在尝试实现这一点.
mainform.html
<标签><span>名称</span>标签><app-userinfo></app-userinfo><!-- 子组件 1 --><app-useracc></app-useracc><!-- 子组件 2 --></表单>
mainform.ts
导出类 MainformComponent 实现 OnInit {表单详细信息:表单组;构造函数(私有表单构建器:FormBuilder){}ngOnInit() {this.formDetail= this.formBuilder.group({姓名:'',用户信息:this.formBuilder.group({用户身份: '',用户名:''}),useracc: this.formBuilder.group({用户名:'',用户转移:''})});}onSubmit(值:用户){调试器;}}
控制台.log
formControlName 必须与父 formGroup 指令一起使用.您需要添加一个 formGroup
是否可以将表单组件嵌套为单独的子组件?
您需要使用 Input()
并将该子 FormGroup
传递给孩子.我在这里稍微更改了一下,并创建了名为 useraccount
的组而不是 useracc
以将控件与组分开:
您父级用户帐户的子组:
...用户帐户:this.formBuilder.group({用户名:'',})...
所以,父组件中相关的子组件标签应该是这样的:
<app-useracc [useraccount]="formDetail.controls.useraccount"></app-useracc>
然后在您的子组件中添加输入:
@Input() useraccount: FormGroup;
模板可能如下所示:
<input formControlName="useracc">
工作 示例
I am working on big form, so i plan to truncate the form into multiple child components which helps for easy integration and maitainbility. Using form builder i am trying to implement this.
mainform.html
<form novalidate (ngSubmit)="onSubmit(formDetail);" [formGroup]="formDetail">
<label>
<span>Name</span>
<input
type="text"
placeholder="Enter emp name"
formControlName="name">
</label>
<app-userinfo></app-userinfo> <!-- Child component 1 -->
<app-useracc></app-useracc> <!-- Child component 2 -->
</form>
mainform.ts
export class MainformComponent implements OnInit {
formDetail: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formDetail= this.formBuilder.group({
name:'',
userinfo: this.formBuilder.group({
userid: '',
userph: ''
}),
useracc: this.formBuilder.group({
useracc: '',
usertransfer: ''
})
});
}
onSubmit(value:User){
debugger;
}
}
Console.log
formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
Is it possible to nested form component as a seperate child ?
You need to use Input()
and pass that sub-FormGroup
to the child. I changed it a bit here and made the group named useraccount
instead of useracc
to separate the control from the group:
Your sub group for useraccount in your parent:
...
useraccount: this.formBuilder.group({
useracc: '',
})
...
So, the related child component tag in the parent should look something like this:
<app-useracc [useraccount]="formDetail.controls.useraccount"></app-useracc>
And then add input in your child component:
@Input() useraccount: FormGroup;
and template could look like this:
<div [formGroup]="useraccount">
<input formControlName="useracc">
</div>
Working sample
这篇关于表单内的多个子组件 - Angular 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!