检测 Angular 形式(非反应性)中的数据是否已更改

Detect if data in an Angular form (not reactive) was changed

我有 Angular 表单(非响应式),在 ngModel 中有数据绑定:

 <form #form="ngForm">
  <input [(ngModel)]="user.name">
  <input [(ngModel)]="user.color">

  <button type="submit">Save</button>
 </form>

如果绑定的数据未更改,如何禁用提交按钮?

您可以像这样使用原始 属性 进行尝试:

<button type="submit" [disabled]="form.pristine">Save</button>

此 属性 检查您的表单在加载后是否发生了变化。

您可以检查脏标志,它告诉您表单是否脏。

<button type="submit" [disabled]="!form.dirty">Save</button>

如果更改其中的某些值,表单会变脏。

点击这里了解更多详情:https://angular.io/guide/forms

根据你的评论'But what if i erase 1 symbol in input and then wright it again (the value is the same, but form was changed)?'我建议这个解决方案。

一般的想法是将表单的初始值存储为单独的对象(只是克隆它)。然后创建一个布尔函数,它简单地遍历键值并将更新的数据与初始数据进行比较。在此之后只需将此函数的结果绑定到您的提交按钮 [disabled]="yourCheckMethod(form.value)".

我遇到过没有表单的情况,尽管我的表单在点击时处理并且没有禁用按钮,但它可以适应此处提出的问题。 Angular 7 个使用 TypeScript:

    <!-- user.component.html -->
    .....
    .....
    <div>
      <input [(ngModel)]="user.name">
      <input [(ngModel)]="user.color">
      <button (click)="save()">Save</button>
    </div>
  
    // user.component.ts
    .....
    .....
    lastObjectHash: string;
    User: user = { name: "joe", color: "blue"};  // with name and color on type User 
    
    // Not really a hash, but let's call it that
    getObjectHash(): Promise<string> {
      return util.encodeBase64(JSON.stringify(this.user));
    }

    ngAfterViewInit(): void {
      this.getObjectHash().then(value => this.lastObjectHash = value);
    }

    save() {
      this.getObjectHash().then(value => { 
        if (this.lastObjectHash === value) {
          alert("You did not change name or color");
          return;
        }
        // Save user changes....
        this.userService.save(this.user);  // Or whatever...
      }); 
    }

    // util.ts
    // Just a utility function to BASE64 encode
    .....
    .....
    export const encodeBase64 = async (textString) => {
      return btoa(textString);
    };