Detect if data in form was changed

六眼飞鱼酱① 提交于 2019-11-27 04:49:34

问题


I have Angular form (not reactive), with data binded in 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?


回答1:


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




回答2:


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.

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)".




回答3:


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.



来源:https://stackoverflow.com/questions/50386974/detect-if-data-in-form-was-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!