角度2:禁用按钮如果表格中有变化
问题描述:
我想检查是否我的表格中至少有一个字段发生了变化。如果这种情况属实,disableButton
将设置为true和false如果有没有更改的形式。下面是我当前的代码:角度2:禁用按钮如果表格中有变化
// this.hold is an array that temporary holds the previous values of
// the form for comparison of the changes in form
if(this.data.process == 'update') {
for(const f in form.value){
if (form.value[f] == this.hold[f])
this.disableButton = true;
else
this.disableButton = false;
}
}
的问题是,当ALL字段 改变了按钮只会关闭。我应该在我的状况或循环中添加什么?
答
当您发现某个值发生更改时,只需添加一个中断。
if(this.data.process == 'update') {
for(const f in form.value){
if (form.value[f] == this.hold[f]){
this.disableButton = true;
}
else{
this.disableButton = false;
break;
}
}
}
答
角度轨迹形成控制值并将状态设置为dirty
(如果其中任何一个已更改)。您不需要手动检查每个控件。只需使用形式的.dirty
属性:
this.disableButton = form.dirty;
如果要排除“回溯” - 添加,然后删除的东西,你可以用markAsPristine()
方法设置控制pristine
状态时更改了该值是一样的它最初是。你可以有初始值的对象:
const initialValues = {prop: 3};
form.valueChanges.subscribe((changes)=>{
for (prop in changes) {
if (changes[prop] === initialValues[prop]) {
form.get(prop).markAsPristine();
}
}
});
仍然无效@YounisArM – Char
当值相同时,你将它设置为true,这与你想要的相反,我已经改变了代码,现在尝试 –
你不需要改变布尔值。但是这工作。谢谢@YounisArM – Char