Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
MMR Avatar asked Dec 07 '22 20:12

MMR


2 Answers

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;
    });
  }

}
like image 67
ranakrunal9 Avatar answered Dec 10 '22 09:12

ranakrunal9


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.

like image 31
user2427829 Avatar answered Dec 10 '22 11:12

user2427829