0

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>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for respond, although I was think about something like this lab.hakim.se/ladda instead. so when user clicked on button loading indicator show up after rxjs subscribe is done automatically disabled indicator . just with passing a true/false to the waitUnit. thanks for the time you spend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.