正如我之前在_2978194中所要求的那样_
我想创建一个嵌套的表单,其中父对象与孩子无关 formControlNames
所以我们说我们有一个组件 componentA.component.ts
@Component({
selector: 'common-a',
template: `
<div [formGroup]="parentForm">
<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() parentForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.parentForm.addControl("valueA1", new FormControl('', Validators.required));
this.parentForm.addControl("valueA2", new FormControl('', Validators.required));
}
}
和主要组成部分 .
@Component({
selector: 'main',
template: `
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<div>
<div *ngFor="let c of myForm.controls.componentA.controls; let i=index" class="form-group">
<common-a [parentForm]="c"></common-a>
</div>
<div>
<button type="submit" [disabled]="myForm.invalid">Register!</button>
<a class="button" (click)="add_component()">Add New</a>
<a class="button" (click)="delete_component()">Delete</a>
</div>
</div>
<pre>form value: <br>{{myForm.value | json}}</pre>
</form>
`
})
export class MainComponent implements OnInit{
@Input('group') public myForm: FormGroup;
add_component() {
const control = <FormArray>this.myForm.controls['componentA'];
control.push(this._fb.group({}));
}
delete_component() {
const control = <FormArray>this.myForm.controls['componentA'];
control.removeAt(this.myForm.length-1);
}
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this._fb.group({
componentA : this._fb.array([this._fb.group({})])
});
}
onSubmit(formValue) {
console.log(formValue);
}
}
我现在的问题是如何使用 patchValue
从服务器 endpoints 获取数据并填充表单数组的值,按需创建新的 FormGroups
,始终与父服务器无关 .
- 我可以看到的一种方法是父母生成新的组 .
这种方法的问题,除了臭的架构,我用我自己的实现覆盖patchValue方法并按需推送这些新组,因为在函数体内我知道有多少,但是孩子的OnInit不会在函数内调用,将值保留为空 .
var self = this;
this.formArray.patchValue = (value: {[key: string]: any}, {onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}) =>{
for(var i = 0; i < Object.keys(value).length; i++ ) {
self.add_new();
}
Object.keys(value).forEach(name => {
if (self.formArray.controls[name]) {
self.formArray.controls[name].patchValue(value[name], {onlySelf: true, emitEvent});
}
});
self.formArray.updateValueAndValidity({onlySelf, emitEvent});
}
- 另一个选择是让孩子提供一个静态函数来暴露它的内部构成 .
我再次认为这是糟糕的设计 .
static generate() {
return new FormGroup({
valueA1: new FormControl('', Validators.required),
valueA2: new FormControl('', Validators.required)
});
}
对于这类问题,你有什么清洁的解决方案吗?
根据我之前的问题,这里还有一个工作plunkr
2 回答
动态控制的替代解决方案 .
1:注入ChangeDetectorRef
2:覆盖patchValue
以下工作: