我在步进器(cdk)中有一个工作正常的表单,我正在重构它以使其动态。我的目标是最后使用json来生成表单内容。
现在我有以下代码:
export class StepperFormsComponent implements OnInit {
private readonly fb: FormBuilder = inject(FormBuilder);
stepperForm: FormGroup;
get formArray() {
return this.stepperForm.get('steps') as FormArray;
}
ngOnInit(): void {
this.initForm();
this.addInitialControlsToForm();
}
initForm(): void {
this.stepperForm = this.fb.group({
steps: this.fb.array([]),
});
}
addInitialControlsToForm(): void {
const stepsArray = this.formArray;
const formData = [
this.fb.group({
userInfo: ['', Validators.required],
}),
this.fb.group({
carInfo: ['', Validators.required],
}),
this.fb.group({
configEnvironments: ['', Validators.required],
configAditionalInfo: ['', Validators.required],
}),
];
formData.forEach(data => {
stepsArray.push(data);
});
}
}
以前的代码可以工作,但我现在想要归档的代码不起作用。 我需要使这个表单更加动态。
因此,我们的想法是使用 formGroupFields 对象创建 getFormControlFields() 方法,并使用 for 迭代模型中的所有属性以推入 formGroupFields,
export class StepperFormsComponent implements OnInit {
private readonly fb: FormBuilder = inject(FormBuilder);
getControls(): AbstractControl[] {
return (<FormArray>this.stepperForm.get('steps')).controls;
}
ngOnInit(): void {
this.initForm();
console.log('formArray', this.formArray.controls.length); // display 1 instead of 3
console.log('formArray step 1', this.formArray.get([0])?.value); // works fine
console.log('formArray step 2', this.formArray.get([1])?.value); // undefined
}
initForm(): void {
const formGroupFields = this.getFormControlsFields();
this.stepperForm = this.fb.group({
steps: this.fb.array([formGroupFields]),
});
}
getFormControlsFields() {
const formGroupFields: FormGroup[] = [];
const formData = [
this.fb.group({
userInfo: ['', Validators.required],
}),
this.fb.group({
carInfo: ['', Validators.required],
}),
this.fb.group({
configEnvironments: ['', Validators.required],
configAditionalInfo: ['', Validators.required],
}),
];
formData.forEach(data => {
formGroupFields.push(data);
});
return formGroupFields;
}
}
所以我的问题是如何将我的表单组推送到 formArray 中?
谢谢
函数返回一个数组,所以需要直接输入返回值,去掉包装形式
initForm(): void {
const formGroupFields = this.getFormControlsFields();
this.stepperForm = this.fb.group({
steps: this.fb.array(formGroupFields), // <- changed here!
});
}