nlr_p nlr_p - 23 days ago 27
TypeScript Question

How to show a loader for 3 sec and hide in angular 2

I want a loader show for 5 sec and hide when i click on a button,
so far i tried

<div *ngIf='showloader' class="form-group loaderformgroup maindivdisplaynone" id="waitresponce" >
<div class="waitresponce">
<img src="assets/img/loader.gif" img-from="assets" alt="loader" class="waitresponceloader"/>
</div>
</div>


resetform() {
this.student = {};
Observable.timer(500).subscribe(() => {
$('#tablebody').addClass('fadding');
this.showloader = true;
Observable.timer(500).subscribe(() =>
$('#tablebody').removeClass('fadding');
this.showloader = false
);
});
}


my ts,

setInterval(() => {
this.showloader = true;
}, 2000);


But it is showing loader after 2000.Can someone please help.Thanks.

Answer

Using setTimeout is not advisable with angular 2. you can use Observable and timer for it :

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/timer';

@Component({
  selector   : 'my-component'
})
export class MyComponent implements OnInit, OnDestroy {
  public showloader: boolean = false;      
  private subscription: Subscription;
  private timer: Observable<any>;

  public ngOnInit() {
    // call this setTimer method when you want to set timer
    this.setTimer();
  }
  public ngOnDestroy() {
    if ( this.subscription && this.subscription instanceof Subscription) {
      this.subscription.unsubscribe();
    }
  }

  public setTimer(){

    // set showloader to true to show loading div on view
    this.showloader   = true;

    this.timer        = Observable.timer(5000); // 5000 millisecond means 5 seconds
    this.subscription = this.timer.subscribe(() => {
        // set showloader to false to hide loading div from view after 5 seconds
        this.showloader = false;
    });
  }

}
Comments