Angular 6 how do I track changes to form fields after certain interval

I have few forms fields in the smart component and some in the child component. and I have a print and submit button.

user enters all the fields and clicks Print button, if print is successful only then submit button will be enabled.The submit button will be disabled if validation fails on any fields too.

after successful print-- 1) Suppose if the user changes anything in any of the fields I want to disable the button --this is OK I can use @Input and @Output to track changes by EVENT EMitter and method calls(IS there a better way to do it please??) 2) If user reverts his changes back to the original values, the way they were after the print, I want to enable the submit button?? How do I do this??

2 answers

  • answered 2018-10-11 20:12 Zze

    For the first part of your question, you don't need anything extra than what angular supplies out of the box with its ngModel state.

    Using ngModel in a form gives you more than just two-way data binding. It also tells you if the user touched the control, if the value changed, or if the value became invalid.

    The NgModel directive doesn't just track state; it updates the control with special Angular CSS classes that reflect the state. You can leverage those class names to change the appearance of the control.

    State Class if true Class if false The control has been
    visited. | ng-touched | ng-untouched The control's value has
    changed. | ng-dirty | ng-pristine The control's value is
    valid. | ng-valid | ng-invalid

    https://angular.io/guide/forms#track-control-state-and-validity-with-ngmodel

    For the second part, you can do something like this:

    public myForm: FormGroup; // form that is in page
    
    this.myForm.valueChanges.subscribe(val => {
        if(val == originalFormValue){
            // code to enable submit button
        }
    });
    

  • answered 2018-10-11 20:53 S.Honderdos

    I won't go over the form itself since I think this is very straight foreword.

    The print button should store a copy of the current form values like this:

    <button (click)="handlePrint(testForm.value)">Print</button>
    
    ...
    
    handlePrint(formValue) {
        this.printedFormValues = {...formValue};
    }
    

    The submit button will only be enabled if both objects are the same using the isEqual function.

    <button [disabled]="!isEqual(testForm.value, printedFormValues)">Send</button>
    

    Comparing objects in Javascript is not the easiest thing so I've used a snippet found somewhere else.

    Working example