【发布时间】:2019-01-31 03:50:15
【问题描述】:
我在 Angular 响应式表单中遇到了一个奇怪的错误。我正在使用 FormArray 创建一个可以添加或删除字段的表单。我还希望能够重置表单,使表单输入的值和数量恢复到原始数量。我目前能够实例化表单,添加字段并删除它们,但是当我按下重置时,我创建的函数首先清空 FormArray,然后使用与最初设置表单相同的过程重新创建字段, 值不能正确显示。不知道为什么会这样,可能是和 html 中用来绑定表单的 formControlNames 有关?
有谁知道导致问题的原因或重置表单值的正确方法是什么?
我在这里创建了一个堆栈闪电战:https://stackblitz.com/edit/angular-reactive-formarray-bug
这是我的组件代码。
import {
Component, ElementRef
} from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
import { ContentTemplate, ContentTemplateEntry, NewContentEntry } from './models';
import {Observable, Subscription, of} from 'rxjs';
import data from './template-data.json';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
public templateForm: FormGroup;
public contentTemplate$: Observable<ContentTemplate>;
public activeTemplate: ContentTemplate;
public templateSub: Subscription;
public entries: ContentTemplateEntry[];
get templateEntries(): FormArray {
return <FormArray>this.templateForm.get('entries');
}
constructor(
private fb: FormBuilder
) {
this.contentTemplate$ = of(data)
}
ngOnInit(): void {
this.templateSub = this.contentTemplate$.subscribe((template: ContentTemplate) => {
this.activeTemplate = {...template};
this.entries = [...template.entries];
this.templateForm = this.fb.group({
entries: this.fb.array([])
});
this._processEntries(this.entries);
});
}
ngOnDestroy(): void {
this.templateSub.unsubscribe();
}
private _buildEntry(entry: ContentTemplateEntry) {
const g = this.fb.group({
id: {value: entry.id},
title: {value: entry.title, disabled: entry.isRequired},
orderNumber: {value: entry.orderNumber},
type: {value: entry.type}
});
return g;
}
private _processEntries(entries: ContentTemplateEntry[]) {
entries.forEach((e, i) => {
this.templateEntries.push(this._buildEntry(e));
});
}
private _getOrderNumber(): number {
return this.templateEntries.length + 1;
}
private _removeItemsFromEntries(): void {
while (this.templateEntries.length > 0) {
this.templateEntries.removeAt(0);
}
}
// reinstantiate using the same approach as before
public resetForm() {
this._removeItemsFromEntries();
this._processEntries(this.entries);
}
public removeEntry(id: number) {
this.templateEntries.removeAt(id);
}
public addEntry() {
this.templateEntries.push(
this._buildEntry(new NewContentEntry({
orderNumber: this._getOrderNumber()
}))
);
}
public save() {
console.log('save triggered');
}
}
【问题讨论】: