How to check for changes in form in Angular 2 using

前端 未结 10 706
轻奢々
轻奢々 2020-12-08 13:53

I have a form with few data fields and two buttons.I want to enable the buttons only if the user makes some changes to the form. I have tried using:

this.for         


        
相关标签:
10条回答
  • 2020-12-08 14:41

    Try the following to see if the form has changed:

    ngOnChanges() {
        if (!!this.form && this.form.dirty) {
            console.log("The form is dirty!");
        }
        else {
            console.log("No changes yet!");
        }      
    }  
    
    0 讨论(0)
  • 2020-12-08 14:54

    I use some trick for my code, i think this not the best solution but somehow it's work for me.

    profile.component.ts:

    tempForm: any
    ngOnInit() {
      this.loadForm();
      this.tempForm = this.form.value
    }
    
    save(): void {
      if (this.tempForm === this.form.value) {
        // Do Save
      } else {
        // Value is Same as initial
      }
    }
    

    hope this solve your question, or maybe just give some inspiration.

    0 讨论(0)
  • 2020-12-08 14:55

    first of all use "NgForm".
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    Then on the "onSubmit()" function do this -

    onSubmit(myForm: NgForm): void {
      let formControls = myForm.controls;
      if(formControls.firstName.dirty) {
        console.log("It's dirty");
      }
      else {
        console.log("not dirty");
      }
    } 
    

    It will definitely work. You can print the whole "myForm" and see for yourselves what all options are available to use.

    0 讨论(0)
  • 2020-12-08 14:55

    you can check for the changes in perticular formcontrol like this:

    this.profileForm.controls['phone'].valueChanges.subscribe(
                    data => console.log('form changes', data)
    
                    );
    
    0 讨论(0)
提交回复
热议问题