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.
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;
});
}
}
If you want to show the loader for 5 sec and hide it, you should set the condition in ng-if to false in setTimeout. Right now you are doing the other way i.e setting to true after 2 sec interval. Thats why it is showing after 2 sec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With