我有表单数组,由于某种原因,我在应用程序输入组件中看不到任何值。如果我定义简单的 formGroup 控件并传递给应用程序输入,我可以看到值。但在 formarray 中发生了一些奇怪的事情。当我记录值时,我看到所有值都未定义
form!: FormGroup<FormType>;
get mtTypeControls(): FormGroup<mtTypesForm>[] {
return this.form.controls.mtTypes.controls as FormGroup<mtTypesForm>[];
}
ngOnInit(): void {
this.form = this.fb.nonNullable.group({
mtTypes: this.fb.array([
this.fb.group({
nameEn: this.fb.control<string | null>('13'),
nameRu: this.fb.control<string | null>('13'),
analyzer: this.fb.control<string | null>('13'),
}),
] as FormGroup<mtTypesForm>[]),
});
this.createForm([]);
private createForm(data: MaintenanceType[]) {
const mtTypesGroup = new FormGroup({
nameEn: new FormControl('123'),
nameRu: new FormControl('333'),
analyzer: new FormControl('333'),
}) as FormGroup<mtTypesForm>;
this.mtTypeControls.push(mtTypesGroup);
@for (group of mtTypeControls; track $index) {
<div class="row margin-top-hg" (click)="test(mtTypeControls)">
<app-input label="Name (ENG)" [formControl]="group.controls.nameEn"></app-input>
<app-input label="Name (RUS)" [formControl]="group.controls.nameRu"></app-input>
问题在于 HTML 的结构。你应该模仿对象结构。
首先我们有一个
[formGroup]="form"
,然后是一个 div
元素,该元素应使用 formArray
定义 formArrayName="mtTypes"
,然后 formArray 将为每个表单组运行 @for
循环。
表单元素存在于 formGroup 内,因此我们应该使用
[formGroupName]="$index"
定义这些元素的逻辑容器。
不要使用
formControl
作为输入属性来传入控件,这是因为它是一个角度指令,并且在使用时已经有一些逻辑在执行,所以使用[control]
来代替。
<form [formGroup]="form">
<div formArrayName="mtTypes">
@for (group of mtTypeControls; track $index) {
<div class="row margin-top-hg" [formGroupName]="$index">
<app-input label="Name (ENG)" [control]="typeAsControl(group.controls['nameEn'])"></app-input>
<app-input label="Name (RUS)" [control]="typeAsControl(group.controls['nameRu'])"></app-input>
<app-input label="Name (RUS)" [control]="typeAsControl(group.controls['analyzer'])"></app-input>
<br/>
</div>
}
</div>
</form>
<form [formGroup]="form">
<div formArrayName="mtTypes">
@for (group of mtTypeControls; track $index) {
<div class="row margin-top-hg" [formGroupName]="$index">
<app-input label="Name (ENG)" [control]="typeAsControl(group.controls['nameEn'])"></app-input>
<app-input label="Name (RUS)" [control]="typeAsControl(group.controls['nameRu'])"></app-input>
<app-input label="Name (RUS)" [control]="typeAsControl(group.controls['analyzer'])"></app-input>
<br/>
</div>
}
</div>
</form>