【发布时间】:2018-12-18 15:51:32
【问题描述】:
我使用以下question 作为我的 FormArray 表单设计的基础。我试图做的事情是使表单与页面上其他地方的更改保持同步,但在此表单中切换一个布尔值/复选框。 (用户有一个他们选择的卡片列表,这个表格显示了这个选择的列表)
不幸的是,ngOnChanges 似乎在不断更新表单,而我的更改正在被覆盖。在我的构造函数中,我检测到值的变化,并打算发出这些变化。不过,
this.contextSummaryForm.dirty
总是为假。 rebuildForm() 上的断点表明该方法每秒被调用多次 - 因此将 contextItem.isEditEnable 更改为 false 将被完全覆盖。我可以阅读我的逻辑并了解为什么会发生这种情况 - 但我真的不明白我应该做什么来允许从其父组件更新 contextList 并允许用户在此处更新表单。
构造函数和变化检测
@Input()
contextList: ContextItem[];
@Output()
contextListChange = new EventEmitter<any>();
valueChangeSubscription = new Subscription;
contextSummaryForm: FormGroup;
isLoaded: boolean = false;
constructor(protected fb: FormBuilder) {
this.createForm();
this.valueChangeSubscription.add(
this.contextSummaryForm.valueChanges
.debounceTime(environment.debounceTime)
.subscribe((values) => {
if (this.isLoaded && this.contextSummaryForm.valid && this.contextSummaryForm.dirty) {
this.contextSummaryForm.value.plans.forEach(x => {
var item = this.contextList.find(y => y.plan.id === x.id);
item.isEditEnabled = x.isEditEnabled;
});
this.contextListChange.emit(this.contextList);
this.contextSummaryForm.markAsPristine();
}
}));
}
表单创建:
createForm(): void {
this.contextSummaryForm = this.fb.group({
plans: this.fb.array([this.initArrayRows()])
});
}
initArrayRows(): FormGroup {
return this.fb.group({
id: [''],
name: [''],
isEditEnabled: [''],
});
}
OnChanges
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
if (propName === 'contextList') {
if (this.contextList) {
this.rebuildForm();
this.isLoaded = true;
}
}
}
}
rebuildForm() {
this.contextSummaryForm.reset({
});
//this.fillInPlans();
this.setPlans(this.contextList);
}
setPlans(items: ContextItem[]) {
let control = this.fb.array([]);
items.forEach(x => {
control.push(this.fb.group({
id: x.plan.id,
name: x.plan.Name,
isEditEnabled: x.isEditEnabled,
}));
});
this.contextSummaryForm.setControl('plans', control);
}
总结一下:我需要一种方法来使用从输入绑定构建的表单数组,该输入绑定跟上变化而不会快速覆盖表单。
【问题讨论】:
-
您可以尝试比较 ngOnChanges 中 contextList 的新旧值,如果它们不同则只调用重建?
-
好建议,我今天试试,我会回来报告的。
-
我认为它缺少父组件代码。多次调用 ngOnChanges 的事实可能是由于父母提供 contextList 的方式
-
能否发布当前组件的父代码 (ts|html) 和 html。