简体   繁体   English

根据值的变化禁用/启用按钮 Angular

[英]Disable/enable button based on change of value Angular

I have a form with different input fields including input[type="file"] and input[type="checkbox"].我有一个包含不同输入字段的表单,包括 input[type="file"] 和 input[type="checkbox"]。 I get values of input form fields with get request from backend and I store them in company variable.我通过从后端获取请求获取输入表单字段的值,并将它们存储在公司变量中。

ngOnInit(): void {
    this.generateForm();

    this.companyService.getCompany().subscribe((response: Company) => {
      this.company = response;

      this.settingsForm.setValue({
        ...this.company,
        certificateUrl: [this.company.certificateUrl],
      });
    });
  }

I first generate form and then get my response from get request so I could set my company variable to the response and set value of form based on values I got.我首先生成表单,然后从 get 请求中得到我的响应,这样我就可以将我的公司变量设置为响应,并根据我得到的值设置表单的值。 The problem is I want to enable button in html whenever my form is valid and changed.问题是我想在我的表单有效和更改时启用 html 中的按钮。 So button should be disabled when no change is made based on previous value.因此,当未根据先前值进行更改时,应禁用按钮。 For example: If we have field name with value 'myName' and I type into input 'my' button should be enabled because change is made comparing to previous value.例如:如果我们有值为“myName”的字段名称并且我在输入中键入“我的”按钮应该启用,因为与以前的值相比发生了变化。 If I type back 'myName' it should be disabled because value is the same as previous.如果我重新输入“myName”,它应该被禁用,因为值与之前的相同。 Same should happen if field is empty and user types in something and for fields type file and checkbox.如果字段为空并且用户输入某些内容并且对于字段类型文件和复选框,则应该发生同样的情况。

This is how I'm currently trying to do it.这就是我目前正在尝试的方式。

inputChanged: boolean = false

ngOnInit() {
    this.settingsForm.valueChanges.subscribe((currentValue) => {
      if (JSON.stringify(currentValue) !== JSON.stringify(this.company)) {
        this.inputChanged = true;
      } else {
        this.inputChanged = false;
      }
    });
}
////

 <button
          [disabled]="!inputChanged || !settingsForm.valid"
          class="btn btn-md text-light"
        >
          Save
        </button>

This is my form这是我的表格

<form class="mt-4" [formGroup]="settingsForm" (ngSubmit)="saveChanges()">
    <div class="row">
      <div class="col-6">
        <div class="form-group">
          <label class="form-label fw-bold">ID</label>
          <input
            formControlName="identificationNumber"
            type="text"
            class="form-control"
          />
        </div>
        <div class="form-group d-none">
          <label class="form-label fw-bold">Id</label>
          <input formControlName="id" type="text" class="form-control" />
        </div>
        <div class="form-group d-none">
          <label class="form-label fw-bold">Country</label>
          <input formControlName="country" type="text" class="form-control" />
        </div>

        <div class="form-group">
          <label class="form-label fw-bold"
            >P</label
          >
          <input formControlName="tin" type="text" class="form-control" />
 
        </div>
        <div class="form-group">
          <label class="form-label fw-bold">Name</label>
          <input formControlName="name" type="text" class="form-control" />
        </div>
      </div>
      <div class="col-6">
        <div class="form-group">
          <label class="form-label fw-bold">City</label>
          <input formControlName="city" type="text" class="form-control" />
        </div>

        <div class="form-group">
          <label class="form-label fw-bold">Address</label>
          <input formControlName="address" type="text" class="form-control" />
        </div>
        <div class="form-group">
          <label class="form-label fw-bold">Postal code</label>
          <input
            formControlName="postalCode"
            type="text"
            class="form-control"
          />
        </div>
        <div class="form-check ms-1">
          <label class="form-check-label fw-bold">Vat</label>
          <input
            formControlName="inVat"
            type="checkbox"
            class="form-check-input"
            [checked]="company?.inVat"
          />
        </div>
      </div>
    </div>

    <div class="row align-items-end justify-content-between">
      <div class="col-8">
        <app-file-upload
          [company]="company"
          formControlName="certificateUrl"
        ></app-file-upload>
      </div>

      <div class="col-4">
        <button
          [disabled]="!inputChanged || !settingsForm.valid"
          class="btn btn-md text-light"
        >
          Save changes
        </button>
      </div>
    </div>
  </form>

But it doesn't work.但它不起作用。 How can I fix this?我怎样才能解决这个问题?

You could make use of other reactive Form attributes您可以使用其他反应式 Form 属性

Using pristine for example例如使用pristine

A control is pristine if the user has not yet changed the value in the UI.如果用户尚未更改 UI 中的值,则控件是原始的。

<button
  [disabled]="settingsForm.pristine || settingsForm.invalid"
  class="btn btn-md text-light"
  >Save</button>

if you need to be more specific in the control values, it becomes more tricky as comparing Javascript objects is not as trivial.如果您需要在控制值中更具体,它会变得更加棘手,因为 比较 Javascript 个对象并不那么简单。

This question is a great deep dive这个问题很深入

The reactive form should have a valid and touched attribute and could be used as following.反应形式应该有一个 valid 和 touched 属性,可以像下面这样使用。

<button
  [disabled]="!settingsForm.touched || settingsForm.invalid"
  class="btn btn-md text-light">Save</button>

I found a solution using objectHash.我找到了一个使用 objectHash 的解决方案。 First install it with npm i -D @types/hash.首先使用 npm i -D @types/hash 安装它。

import * as objectHash from 'object-hash';

this.settingsForm.valueChanges.subscribe((currentValue) => {
      if (objectHash.sha1(currentValue) !== objectHash.sha1(this.company)) {
        this.inputChanged = true;
      } else {
        this.inputChanged = false;
      }
    });

////
<button
    [disabled]="!inputChanged || !settingsForm.valid"
    class="btn btn-md text-light"
    >
    Save
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM