我如何检测/观看“脏状态"?正确的角度2形式? [英] How can I detect/watch "dirty-status" of an angular2-form in the right way?

查看:51
本文介绍了我如何检测/观看“脏状态"?正确的角度2形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2中有一个表单(例如)

I have a form in Angular2 (e.g)

<form id="myLovelyForm" name="myLovelyForm" #myLovelyForm="ngForm">
    <label [attr.for]="myLovelyCheckbox">
      <input [attr.id]="myLovelyCheckbox" type="checkbox"
             [(ngModel)]="myLovelyCheckbox">
      <span class="myLovelyCheckbox">myLovelyCheckbox</span>
    </label>
</form>

和一个动画,如果表单很脏,则应该开始动画:

and an animation, which should start, if the form is dirty:

<div 
    id="myLovelyNotification" 
    class="myLovelyNotification" 
    [@notification]="myLovelyForm.form.dirty">
.....
.....
</div>

如果我设置[@notification] = true,则动画可以正常工作,但是如果我触摸表单并更改元素,则我的myLovelyForm.dirty不会触发.

The animation works properly if I set [@notification] = true, but my myLovelyForm.dirty does not fire, if I touch the form and change an element.

如果@notification为false,则动画将停止,即如果之前选中了该复选框,并且我错误地取消选择了该复选框并再次选择它,则该表单不是原始的(被触摸的)但不再脏了,因此动画应该停止.如果我手动设置@notification = false,它将正常工作.

If the @notification is false, the animation stops, i.e. if the checkbox was selected before and I unselect it mistakenly and select it again, the form is not pristine (touched) but not dirty anymore, therefore the animation should stop. If I set the @notification = false manually, it works properly.

最大的问题是:如何以正确的方式检测/观察angular2形式的脏状态"?

The big question is: How can I detect/watch "dirty-status" of an angular2-form in the right way?

推荐答案

您可以订阅表单更改:

this.physicalForm.valueChanges
   .map((value) => {
      return value;
   })
   .subscribe((value) => {
      if(this.selectedPhysical.weight != this.physicalForm.value.weight)  {      
        this.selectedPhysical.weight = this.physicalForm.value.weight;
      }
      this.isDirty == this.physicalForm.touched;
   });

如果触发此事件,则说明您的表单很脏.

If this event fires, then you know your form is dirty.

这是我实际应用中的一个示例(nut.abbr是formcontrolName):

this is an example from my actual app (nut.abbr is the formcontrolName):

ngOnInit() {
   for (let nut of this.userSettings.nutrientData) {
      this.foodSettingsForm.controls[nut.abbr].valueChanges
         .subscribe(v => { console.log("value: ", v); this.completeValueChange(nut.abbr, v); });
   }
}

completeValueChange(field: string, value: boolean) {
   this.isChanged = true;
   Nutrient.updateNutrient(field, value, this.userSettings.nutrientData);
}

这篇关于我如何检测/观看“脏状态"?正确的角度2形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆