如何显示装载机3秒钟并隐藏角度2

时间:2016-11-09 09:33:26

标签: angular typescript

我希望装载机显示5秒钟并在我点击按钮时隐藏, 到目前为止我试过

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

我的ts,

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

但它在2000年之后显示装载机。可以请某人帮忙。谢谢。

3 个答案:

答案 0 :(得分:8)

建议不要使用setTimeout角度2.您可以使用Observabletimer

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

}

答案 1 :(得分:1)

如果要显示加载程序5秒并隐藏它,则应在setTimeout中将条件设置为ng-if为false。现在你正在做另一种方式,即在2秒间隔后设置为真。这就是它在2秒后显示的原因。

答案 2 :(得分:-1)

2000是2秒。试试5000 而不是setInterval使用setTimeout,它只会发生一次