【问题标题】:How to detect form value is updated or not on click of update button Angular如何在单击更新按钮Angular时检测表单值是否更新
【发布时间】:2020-01-22 10:08:09
【问题描述】:

我的表单中有超过 15 个字段,如果用户在编辑模式下打开表单,并且表单的值未更新,则单击更新按钮时显示消息值未更改。否则,如果表单值发生更改,则会显示消息“数据已更新”。

我不需要更新值,我只需要在按钮单击时检查值是否更新。

以下是我尝试过的代码,但这不适用于更新按钮点击。

HTML

<div>
  <form id="editfrm" [formGroup]="Editunit">
    <div>
    <input type="text" formControlName="name"  />
    </div>
    <div>
    <input type="text" formControlName="code"  />
    </div>
 </form>
 </div>

 <footer>
<button class="btn btn-secondary" type="reset" (click)="update(Editunit.value)">Edit</button>
</footer>

//Component.ts 文件

 update(Editunit?) {
    this.Editunit.valueChanges.subscribe((data) => {
        if(data is changed){
            alert("Data updated");
        }else{
             alert("form not updated");
        }      
      return;
    });   
}

【问题讨论】:

  • 或许你可以看看FormGroup Pristine
  • 你能否添加一些代码来检查按钮点击时的原始和脏污?

标签: javascript angular angular-material


【解决方案1】:

您可以订阅表单的 valueChanges 并使用成对检查是否有更改,否则如果您“更改”具有相同值的输入 Angular 给您更改了

changed:boolean=false;

this.form.valueChanges.pipe(
      takeWhile(()=>!this.changed),
      startWith(this.form.value),
      pairwise()
      ).subscribe(([old,value])=>{
        let change=false;
        Object.keys(old).forEach(k=>{
          change=change || old[k]!=value[k]
        })
      this.changed=change;
    })

或者简单地获取变量中的旧值,然后检查值

this.oldValues={...this.form.value} //after create the form

isChanged()
{
  let change=false;
  Object.keys(this.oldValues).forEach(k=>{
     change=change || this.oldValues[k]!=this.form.value[k]
  })
  return change
}

stackblitz

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2012-07-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多