我是相当新的angular2而且在过去的几天我一直在试图使用模型驱动形式重用组件
创建可重用表单组件因此,可以说,我们有一个组件componentA.component.ts
@Component({
selector: 'common-a',
template: `
<div [formGroup]="_metadataIdentifier">
<div class="form-group">
<label>Common A[1]</label>
<div>
<input type="text" formControlName="valueA1">
<small>Description 1</small>
</div>
<div class="form-group">
<label>Common A[2]</label>
<div>
<input type="text" formControlName="valueA2">
<small>Description 2</small>
</div>
</div>
`
})
export class ComponentA implements OnInit{
@Input('group')
public myForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this._fb.group({
valueA1 : ['', [Validators.required]],
valueA2 : ['', [Validators.required]],
});
}
}
成分b componentB.component.ts
@Component({
selector: 'common-b',
template: `
<div [formGroup]="_metadataIdentifier">
<div class="form-group">
<label>Common B</label>
<div>
<input type="text" formControlName="valueB">
<small>Description</small>
</div>
</div>
`
})
export class ComponentB implements OnInit{
@Input('group')
public myForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm= this._fb.group({
valueB : ['', [Validators.required]]
});
}
}
我的问题是如何通过CA n我使用这两个子组件构成一个表单,而不会将输入控件移动到主要组件。 例如一个main.component.ts
@Component({
selector: 'main',
template: `
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<div>
<common-a [group]="formA"></common-a>
<common-b [group]="formB"></common-b>
<div>
<button>Register!</button>
</div>
</div>
</form>
`
})
export class Main implements OnInit{
@Input('group')
public myForm: FormGroup;
public formA : FormGroup;
public formB : FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this._fb.group({
//how can I compose these two sub forms here
//leaving the form control names agnostic to this component
});
}
}
这背后的想法的概念是建立一个分享他们的一些积木的许多复杂的形式。
也就是说,我不希望我的Main
组件知道的formControlNames
名称[valueA1
,valueA2
,valueB
],但自动将它们插入,并在顶层表单组更新/验证。
任何想法或指向正确的方向将是有益的。
谢谢很多,这真的很有帮助,眼睛开放:) – stevengatsios
新角度,并立即开始与模型驱动的形式。出于好奇,这种共享* FormGroup *字段的方法是使用推荐方法还是解决方法?我正在构建一个复杂的系统,我尝试着重于开发小型组件,然后在父子关系(4-5级)中重用它们。 – Raf