How to forbid to press "next" button until all of inputs are updated

Viewed 80

I've got 30+ inputs on a single page. Each input has a callback on ng-blur (focus loss) which calls a remote API through $http AngularJS service. Each api request is running asynchronously in parallel. User may edit an input several times. Each time the ng-blur event is fired the data is sent to the server.

I also have the "next" button at the bottom of the page which user presses when he/she is done editing the inputs on a page. How to forbid user to press the "next" button until each of api PUT promises is finished? And what to do if some of HTTP requests failed because of 500 on server?

3 Answers

Use a flag finished in the component.

In the view =>

<button type="submit" [disabled]="!finished">Add</button>

In the component =>

public finished = false;

In side the Promise =>

   let promise1 = Promise.resolve(3);
   let promise2 = 42;
   let promise3 = new Promise(function(resolve, reject) {
      setTimeout(resolve, 100, 'foo');
    });

Promise.all([Promise1,Promise2,....]).then((...)=> {
  finished =true; // your button will be enabled!!
})

You can learn more from here

OR

You can use flag for each and every promise =>

public promiseF1 = false;
public promiseF2 = false;
public promiseF3 = false;
etc...

For each and every call, at the start make it false and when the call end make it true.

So the html will look like this =>

<button type="submit"[disabled]="!promiseF1 && !promiseF2 && !promiseF3 && etc...">
 Add
</button>

Put "required" input parameter in each of the input fields, this way you can make sure that all the response from different promises are getting filled before submit button gets active.

And then check for form validity on submit button.

<form  #form="ngForm">
    //Your input fields with required paramets

  <button type="submit" [disabled]="form.invalid">Next</button>

</form>

I've solved this by implementing some semaphore-like solution. Initially the semaphore counter is zero. I increment the counter every time the the promise is created and decrement it every time the promise resolves or rejects (in .finally()). Whenever the counter is zero the "next" button is available for user.

Related