Dark star
Dark star

Reputation: 5832

How to create angular2 loading indicators button

How can I create simple indicators loading button with directive feature in angular2, so then can be use everywhere.also with control access in parent component?

// Something like this
<button loading [waitUntil]="listenToParent">Submit</button>

Upvotes: 0

Views: 1472

Answers (1)

Siddharth Sharma
Siddharth Sharma

Reputation: 1711

You can create a directive for the same like this:

@Directive({
  selector:'[loading]',
  inputs: ['waitUntil']
})
class Loading {
  private dataPromise: Promise;
  constructor(el: ElementRef){

  }

  set waitUntil(data:Promise) {
    this.dataPromise = data;
    this.dataPromise.then(function(message) {
      alert(message);
    })

  }
}

Component for the implementation of the same:

@Component({
  selector: 'my-app',
  template: `
  <h2>Hello World</h2>
  <button loading [waitUntil]="thePromise">button</button>`,
  providers: [], 
  directives: [Loading]
})
export class App implements ngAfterViewInit{
  name:any;
  thePromise: Promise ;
  constructor() {
   this.thePromise = new Promise((resolve, reject) => {
      setTimeout(function() { resolve("API call complete hide loader.");}, 1000);
    });
  }

  ngAfterViewInit(){

  }
}

From above example, you can see how a promise that was declared in the parent was passed and fulfilled in the directive, in the constructor of the directive you get the elementRef which can be used to manipulate the element, so you can show a loading symbol or disable the button element till the promise is fulfilled, once is promise is fulfilled the button can be enabled etc. depending on the requirement.

Plnkr for the same: http://plnkr.co/edit/IptHfR?p=preview

Upvotes: 1

Related Questions