MMR
MMR

Reputation: 3029

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.

Upvotes: 5

Views: 24066

Answers (3)

ranakrunal9
ranakrunal9

Reputation: 13558

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

}

Upvotes: 15

user2427829
user2427829

Reputation: 128

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.

Upvotes: 1

vakho papidze
vakho papidze

Reputation: 465

2000 is 2 sec. try 5000 and instead of setInterval use setTimeout, it will happen only once

Upvotes: 0

Related Questions