Search code examples
angulartypescriptsubscription

I need to listen if there any changes in the form, make enable/disable SAVE button if there changes or not | Angular


Have issue with listening any changes on a page there is some information, and even if no changes SAVE button active for click

ngOnInit(): void {
        this.createConfigForm()

        this.configFilterForm.valueChanges.pipe(takeUntil(this.unsubscribeAll$)).subscribe(value => {
            value
        })
 }
<!-- ADD BUTTON -->
            <button
                *ngIf="isUpdate()"
                [disabled]="configFilterForm"
                mat-raised-button
                class="add-config-button"
                (click)="onSave()"
                trackClickSnowplow
                id="config-form_save_button"
            >
                <span>SAVE</span>
            </button>


Solution

  • Listen to the form changes like you are doing now, and every time there is a change, enable the button. Disable the button when you click the button, it will stay disabled until change happens. Something like:

    configFilterForm: FormGroup;
    isDisabled = true;
    
    constructor(private fb: FormBuilder) {
      this.configFilterForm = this.fb.group({
        input1: ['hello']
      });
    
      this.configFilterForm.valueChanges.pipe(
        takeUntil(this.unsubscribeAll$)
      ).subscribe(value => {
         this.isDisabled = false;
      });
    }
    

    And button:

    <button [disabled]="isDisabled">Submit</button>
    

    HERE'S A DEMO

    BTW, I see you are calling some function *ngIf="isUpdate()" on your button. Please don't do that, they are called on each change detection and can really slow down your application. Use variables instead!