我面临与FormGroups和ControlValueAccessors相关的问题。
我制作了一个根编辑器组件,其中包含一个FormGroup。在它里面,我有一些其他的组件,它们都由多个FormGroups、FormArrays和FormControl组成。一个漂亮的嵌套结构。它们也都实现了ControlValueAccessor接口。
因此,我的根编辑器组件模板如下所示:
editor.component.html
<form [formGroup]="editorForm" (ngSubmit)="onSubmit()">
<app-section-tax-payer-data formControlName="taxPayerData"></app-section-tax-payer-data>
<app-section-regions formControlName="regions"></app-section-regions>
<app-section-other-entities formControlName="others"></app-section-other-entities>
</form>
编辑器控制器如下所示:
编辑器.component.ts
export class EditorComponent implements OnInit {
editorForm = this.fb.group({
taxPayerData: null,
regions: null,
others: null
});
组件如下所示:
section-regions.component.ts
export class SectionRegionsComponent implements OnInit, ControlValueAccessor {
regionsFormGroup = this.fb.group({
rows: this.fb.array([]),
creditSum: { value: null },
debtSum: { value: null },
balance: { value: null }
});
constructor(private fb: FormBuilder) {
this.rows.forEach((i) => {
// Create form controls for each row
this.rowsFormArray.push(this.fb.group({
regionCode: null,
tributeCode: null,
instalment: null,
referenceYear: [null, { validators: [Validators.pattern("^[0-9]*$")] }],
debtAmount: [null, { validators: [Validators.pattern("^[0-9]*$")] }],
creditAmount: [null, { validators: [Validators.pattern("^[0-9]*$")] }],
}))
}
}
我的问题如下:如果我以这种方式将其他 FormControls 添加到editorForm,我会将它们设置为 null,从而丢失它们的内部结构(FormArray 包含包含 FormControls 的 FormGroups)。
有没有办法检索它们并告诉 Angular “按原样”使用它们?每个组件已经在初始化它们的内部结构,我不明白为什么在添加 FormControl 时需要指定一个值。
感谢任何人的帮助,我刚开始使用 Angular(来自 AngularJS),我有点迷路了!