要创建具有动态添加输入字段的表单。
addPers()
和addBacklogs()
创建新字段。我会用一个函数替换这两个函数,在参数中我选择在这里建立哪个字段是我想象的原型:
addField(groupparam: FormGroup, fieldparam : FormArray, functionAdd: FormGroup): void {
const control = < FormArray > this.<groupparam>.controls[fieldparam];
control.push(this.<functionAdd()>);
}
这是我的 TS文件
export class AjoutProjetComponent implements OnInit {
isLinear = false;
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
thirdFormGroup: FormGroup;
constructor(private _formBuilder: FormBuilder) {}
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
leadProj: ['', Validators.required],
nomProj: ['', Validators.required],
descProj: ['', Validators.required],
besProj: ['', Validators.required],
});
this.secondFormGroup = this._formBuilder.group({
pers: this._formBuilder.array([this.createItem()])
});
this.thirdFormGroup = this._formBuilder.group({
backlog: this._formBuilder.array([this.createFonct()])
});
console.log(this.secondFormGroup);
}
createItem(): FormGroup {
return this._formBuilder.group({
name: ['', Validators.required],
poste: ['', Validators.required],
});
}
createFonct(): FormGroup {
return this._formBuilder.group({
fonctionnalite: ['', Validators.required],
userStory: ['', Validators.required],
});
}
deleteItem(index: number) {
const control = < FormArray > this.secondFormGroup.controls['pers'];
control.removeAt(index);
}
addPers(): void {
const control = < FormArray > this.secondFormGroup.controls['pers'];
control.push(this.createItem());
}
addBacklog(): void {
const control = < FormArray > this.thirdFormGroup.controls['backlog'];
control.push(this.createFonct());
}
然后在HTML中而不是传递AddBacklog()
或AddItem()
我会传递一个具有足够参数的同一个函数addField(groupparam, fieldparam, functionAdd)
答案 0 :(得分:0)
我不确定我是否理解你,但我认为你的解决方案会运作得很好。例如,您可以使用字符串:
addField(groupparam: string, fieldparam: string, functionAdd: string): void {
const control = < FormArray > this[groupparam]controls[fieldparam];
control.push(this[functionAdd]()>);
}
然后执行类似
的操作this.addField('secondFormGroup', 'pers', 'createItem')
你的代码中的。
这是否是整个用例的最佳解决方案,您必须知道。