Search code examples
settimeoutloadingangular-ng-ifionic5

How use setTimeout for *ngIf in angular 10 for the ionic spinner


I'll have an ionic loading indicator that I'll want to show after 2 seconds of loading if the application still loading data from a server else don't show it. This is the html of the spinner.

<!-- Loading -->
    <div class="ion-text-center" *ngIf="isLoading && timer == 0">
      <ion-spinner name="dots" color="light"></ion-spinner>
    </div>

In the page component I'll set isLoading to true each time new posts are loaded. In the setPostData I'll set it back to false. But combining this with the timer doesn't work.

posts: any = [];
timer: any = 0;
isLoading: boolean;

constructor(){...}

getPostData(){
    this.timer = setTimeout(() => {}, 2000);
    this.isLoading = true;

    this.postService.getPosts().subscribe(
        (result) => {
            this.setPostData(result);
        }
    );

}

setPostData(data){
    this.posts = data.posts;
    this.isLoading = false;
}

Solution

  • I'll found another way to do it. Create a timer(setTimeout) and bind the toggleLoading function. In the setPostData function clear the created timer. So after 2500 miliseconds the loading starts. If 2500 miliseconds is not reached the timer is cleared and the loading dots are not displayed as wished.

    posts: any = [];
    timer
    isLoading: boolean;
    
    constructor(){...}
    
    toggleLoading(){
        this.isLoading = !this.isLoading;
    }
    
    getPostData(){
        this.timer = setTimeout(this.toggleLoading.bind(this), 2500);
    
        this.postService.getPosts().subscribe(
            (result) => {
                this.setPostData(result);
            }
        );
    
    }
    
    setPostData(data){
        this.posts = data.posts;
        if(this.timer) {
            clearTimeout(this.timer);
        }
        this.isLoading = false;
    }