File

src/app/shared/network-status/network-status.component.ts

Implements

OnInit

Metadata

changeDetection ChangeDetectionStrategy.OnPush
selector app-network-status
styleUrls ./network-status.component.scss
templateUrl ./network-status.component.html

Index

Properties
Methods

Constructor

constructor(cdr: ChangeDetectorRef)
Parameters :
Name Type Optional
cdr ChangeDetectorRef No

Methods

handleNetworkChange
handleNetworkChange()
Returns : void
ngOnInit
ngOnInit()
Returns : void

Properties

online
Type : boolean
Default value : navigator.onLine
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { checkOnlineStatus } from '@src/app/_helpers';

@Component({
  selector: 'app-network-status',
  templateUrl: './network-status.component.html',
  styleUrls: ['./network-status.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NetworkStatusComponent implements OnInit {
  online: boolean = navigator.onLine;

  constructor(private cdr: ChangeDetectorRef) {
    this.handleNetworkChange();
  }

  ngOnInit(): void {
    window.addEventListener('online', (event: any) => {
      this.online = true;
      this.cdr.detectChanges();
    });
    window.addEventListener('offline', (event: any) => {
      this.online = false;
      this.cdr.detectChanges();
    });
  }

  handleNetworkChange(): void {
    setTimeout(async () => {
      if (this.online !== (await checkOnlineStatus())) {
        this.online = await checkOnlineStatus();
        this.cdr.detectChanges();
      }
      this.handleNetworkChange();
    }, 3000);
  }
}
<nav class="navbar navbar-dark background-dark">
  <h1 class="navbar-brand">
    <div *ngIf="online; then onlineBlock; else offlineBlock"></div>
    <ng-template #offlineBlock>
      <strong style="color: red">OFFLINE </strong>
      <img width="20rem" src="assets/images/no-wifi.svg" alt="Internet Disconnected" />
    </ng-template>
    <ng-template #onlineBlock>
      <strong style="color: lawngreen">ONLINE </strong>
      <img width="20rem" src="assets/images/wifi.svg" alt="Internet Connected" />
    </ng-template>
  </h1>
</nav>

./network-status.component.scss

Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""