Disable and enable two buttons for same condition(while typing in forms) angular

1000 Views Asked by At

I have a formfield named value. I have a add button. When I click the add button it duplicates the form field. I have written code in such a way that when I enter a value(say 40) in formfield and then click add button and enter another value say (50),I have a function which adds the sum of these values and compare it with the Totalvalue above.If its greater than the totalvalue the a error message pops up.

Now what I need is that when my sum of the form values is equal to the totalvalue above I need to disable the add button and enable my submit button.I tried it a certain way by using [disabled]="isin" and assigned boolean to disable and enable. But thsi didnt work as I expected.(Because if I enter a value greater than totalvalue the add button gets disabled and when I hit backspace its still disabled)

Note:Please comment below If my question was unclear

My stackblitz link: https://stackblitz.com/edit/angular-ivy-fc8tcl?file=src%2Fapp%2Fapp.component.html

2

There are 2 best solutions below

5
On BEST ANSWER

In your SB example, the logic around switching the value of this.isin doesn't get re-triggered after it's been set to true.

A more straightforward solution would be to replace

if (this.total <= sum) {
  this.isin = !this.isin;
}

with

this.isin = this.total === sum;

Also, change the [disabled] binding on the Add button to use the returned value from the checkTotal call, and use isin to bind to the Submit button, like this

<button ... [disabled]="!checkTotal()" ><span class="fa fa-plus"></span>Add</button>
...
<button type="submit" ... [disabled]="!isin">Submit</button>

Working SB link: https://stackblitz.com/edit/angular-ivy-mwywpt?file=src/app/app.component.ts

One more thing to note: checkTotal() doesn't get called when a value is deleted, so you have to change one of the input values to get the value of isin to re-calculate

0
On

You're definitely on the right track, but if you want to have that behavior you need to subscribe on the formControl's valueChanges event, there you check if the sum is equal, greater or lesser than your expected value, and enable/disable the boolean for the buttons.

https://angular.io/api/forms/AbstractControl#valueChanges