Hello to all, welcome to therichpost.com. In this post, I will tell you, Angular 9 show loader before API data loads.
I am doing this in Angular 9 version. This is very interesting post because I liked it very much.
In this post, loader will show according to content load and this is the awesome thing.
I am calling Angular loader before API data will load successfully and I am getting API data with Angular HTTP Client.
Here is the working code, you need to follow carefully:
1. Here is the code, you need to add into app.module.ts file:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // we need this because we are calling API to get records import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. You need to add below code into your app.component.ts file:
import { Component } from '@angular/core'; // HttpClient will call the API and get data import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angularloader'; //Initiate loader loader = true; post : any; constructor(private http: HttpClient) { this.http.get('https://project/posts').subscribe(data => { this.post = data; this.loader = false; }, error => console.error(error)); } }
3. You need to add below code into app.component.html file:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <div class="loader" *ngIf="loader"> <div class="bar"></div> </div> <div class="jumbotron text-center"> <h1> Welcome to {{ title }}!</h1> <p>Resize this responsive page to see the effect!</p> </div> <div class="container"> <div class="row"> <ul> <!-- Get The API Data --> <li *ngFor="let Posts of post"> <span>{{ Posts.id }}</span> <h2>{{ Posts.title }}</h2> <p>{{ Posts.body }}</p> </li> </ul> </div> </div>
4. You need to add the below code into app.component.css file to styling loader:
@keyframes loader-animation { 0% { left: -100%; } 49% { left: 100%; } 50% { left: 100%; } 100% { left: -100%; } } .loader { height: 5px; width: 100%; overflow: hidden; } .loader .bar { position: relative; height: 5px; width: 100%; background-color: dodgerblue; animation-name: loader-animation; animation-duration: 3s; animation-iteration-count: infinite; animation-timing-function: ease-in-out; }
This is it, if you have any query regarding this post, then please let me know.
Jassa Jatt
Thank you
Recent Comments