简体   繁体   English

单击更新按钮 Angular 如何检测表单值是否更新

[英]How to detect form value is updated or not on click of update button Angular

I have more than 15 fields in the form, If user open the form in Edit mode, and the value of the form is not updated, then it shows message value is not changed on click of update button.表单中有超过 15 个字段,如果用户在编辑模式下打开表单,并且表单的值未更新,则单击更新按钮时显示消息值未更改。 Otherwise if the form value is changed then it shows message "Data updated".否则,如果表单值发生更改,则会显示消息“数据已更新”。

I don't need updated value, i just need to check the value is updated or not on button click.我不需要更新的值,我只需要检查按钮单击时值是否更新。

Below is my code which i tried but this is not working on update button click.下面是我尝试过的代码,但这不适用于单击更新按钮。

HTML 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 file //组件.ts文件

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

you can subscribe to valueChanges of the form and use pairwise to check if there was a change else if you "change" an input with the same value Angular give you changed您可以订阅表单的 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;
    })

Or simply get the olds values in a variable, and check the values或者简单地获取变量中的旧值,然后检查值

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
}

See stackblitz堆栈闪电战

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

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