【问题标题】:Angular 2: disable button if there are changes in formAngular 2:如果表单发生更改,则禁用按钮
【发布时间】:2017-12-30 22:29:02
【问题描述】:

我想检查我的表单中是否至少有一个字段被更改了。如果这种情况为真,disableButton 将设置为 true,如果表单中没有更改,则设置为 false。以下是我当前的代码:

// this.hold is an array that temporary holds the previous values of 
// the form for comparison of the changes in form

if(this.data.process == 'update') {
   for(const f in form.value){
       if (form.value[f] == this.hold[f])
           this.disableButton = true;
       else
           this.disableButton = false;
   }
}

问题是,该按钮仅在 ALL 字段为 改变了。我应该在条件或 for 循环中添加什么?

【问题讨论】:

    标签: forms angular typescript field angular-forms


    【解决方案1】:

    Angular 跟踪表单控件的值并将状态设置为dirty(如果其中任何一个发生更改)。您无需手动检查每个控件。只需使用表单的.dirty 属性:

    this.disableButton = form.dirty;
    

    如果您想排除“回溯” - 添加然后删除某些内容,您可以使用markAsPristine() 方法将控件设置为pristine 状态,当更改的值与最初相同时。您可以拥有初始值的对象:

    const initialValues = {prop: 3};
    form.valueChanges.subscribe((changes)=>{
        for (prop in changes) {
           if (changes[prop] === initialValues[prop]) {
               form.get(prop).markAsPristine();
           }
        }
    });
    

    【讨论】:

    • 但是如果用户删除更改,它仍然会很脏@Maximus
    • 你的意思是如果有值a 然后用户添加了b 所以它现在是ab 然后删除b 和a 保持原样改变?
    • 很脏,是的,但是您可以添加一个“重置”按钮来调用 NgForm 对象上的 .reset() 函数,以再次将状态重置为原始状态,如果这适合您的需要。如果您必须允许用户手动返回初始状态,那么恐怕您必须手动比较每个字段...
    • @Char, @Amit setPrisine() 方法是更好的选择
    • 我认为 setPristine 是 angularjs 名称,我认为 angular2/4 使用 markAsPristine 但我不会使用它,因为您必须手动确定它是否与以前的值相同,我仍然认为重置是更好的选择。
    【解决方案2】:

    pristine 属性(或相反的 dirty 属性)是您所追求的。它在AbstractControl 类上定义,并指示您的FormControl、FormGroup 或FormArray 是否已进行任何更改。

    【讨论】:

      【解决方案3】:

      当你发现某个值发生变化时,只需添加一个中断即可。

      if(this.data.process == 'update') {
         for(const f in form.value){
             if (form.value[f] == this.hold[f]){
                 this.disableButton = true;
      
             }    
             else{
                this.disableButton = false;
                break;
              }
      
         }
      }
      

      【讨论】:

      • 当值相同时,您将其设置为 true ,这与您想要的相反,我已更改代码,立即尝试
      • 您不需要更改布尔值。但这有效。谢谢@YounisArM
      【解决方案4】:
      editForm: FormGroup;
          this.editForm = this.fb.group({
            editCountry: ['', Validators.required],
            editDate: ['', Validators.required],
            editHolidayName: ['', Validators.required],
          });
           <div>
          <button [disabled]="!editForm.dirty" type="button" class="btn btn-primary miracle-submit m-t-5">Save</button>
          </div>
      

      【讨论】:

        猜你喜欢
        • 2019-07-19
        • 1970-01-01
        • 2020-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 2017-06-30
        相关资源
        最近更新 更多