Spinner for Loading

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SpinnerDemo</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  }
}

app.component.html

<app-users></app-users>

users.component.ts

import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
 })

export class UsersComponent implements OnInit {
  users: Object; // <-- Do not use $ at the end of a variable unless it is an observable
  loading = true;
  constructor(private data: DataService) { }
  ngOnInit() {

    this.data.getUsers().subscribe(data => {
      this.users = data;
    },
    (error) => {},
    () => {this.loading = false; }
    );
  }
}

user.component.html

<div *ngIf="loading else loaded">
  <div class="container-fluid">
    <div class="row" style="line-height: 40;">
      <div class="col-12" style="text-align: center;">
        <div class="spinner-border" role="status"></div>
      </div>
    </div>
  </div>
</div>

<ng-template #loaded>
  <div *ngFor="let user of users">{{user.name}}</div>
</ng-template>

Output :

Leave a Comment