typescript 检测 Angular 形式(非响应式)中的数据是否已更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50386974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect if data in an Angular form (not reactive) was changed
提问by Vladimir Humeniuk
I have Angular form (not reactive), with data binded in ngModel:
我有 Angular 形式(非反应式),数据绑定在 ngModel 中:
<form #form="ngForm">
<input [(ngModel)]="user.name">
<input [(ngModel)]="user.color">
<button type="submit">Save</button>
</form>
How can i disable submit button if binded data has not been changed?
如果绑定数据未更改,如何禁用提交按钮?
回答by Pranay Rana
do this , check for dirty flag, which tells form dirty or not
这样做,检查脏标志,它告诉表单脏与否
<button type="submit" [disabled]="!form.dirty">Save</button>
form becomes dirty if you change some value in it.
如果您更改其中的某些值,表单就会变脏。
Check here for detail : https://angular.io/guide/forms
在这里查看详细信息:https: //angular.io/guide/forms
回答by shohrukh
According to your comment 'But what if i erase 1 symbol in input and then wright it again (the value is the same, but form was changed)?' I suggest this solution.
根据您的评论“但是,如果我删除输入中的 1 个符号然后再次编写它会怎样(值相同,但形式已更改)?” 我建议这个解决方案。
The general idea is to store the initial value of the form as separate object (just cloning it). And then create a boolean function which simply iterate through the key-values and compare Updated data with the Initial data. After this just bind the result of this function to your submit button [disabled]="yourCheckMethod(form.value)
".
一般的想法是将表单的初始值存储为单独的对象(只需克隆它)。然后创建一个布尔函数,它简单地遍历键值并将更新的数据与初始数据进行比较。在此之后,只需将此函数的结果绑定到您的提交按钮[disabled]="yourCheckMethod(form.value)
“。
回答by ochs.tobi
You can try it with the pristine property like this:
您可以像这样使用原始属性尝试它:
<button type="submit" [disabled]="form.pristine">Save</button>
This property checks if your form has changed since it was loaded.
此属性检查您的表单自加载以来是否已更改。