src/app/shared/network-status/network-status.component.ts
changeDetection | ChangeDetectionStrategy.OnPush |
selector | app-network-status |
styleUrls | ./network-status.component.scss |
templateUrl | ./network-status.component.html |
Properties |
Methods |
constructor(cdr: ChangeDetectorRef)
|
||||||
Parameters :
|
handleNetworkChange |
handleNetworkChange()
|
Returns :
void
|
ngOnInit |
ngOnInit()
|
Returns :
void
|
noInternetConnection |
Type : boolean
|
Default value : !navigator.onLine
|
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-network-status',
templateUrl: './network-status.component.html',
styleUrls: ['./network-status.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NetworkStatusComponent implements OnInit {
noInternetConnection: boolean = !navigator.onLine;
constructor(private cdr: ChangeDetectorRef) {
this.handleNetworkChange();
}
ngOnInit(): void {}
handleNetworkChange(): void {
setTimeout(() => {
if (!navigator.onLine !== this.noInternetConnection) {
this.noInternetConnection = !navigator.onLine;
this.cdr.detectChanges();
}
this.handleNetworkChange();
}, 5000);
}
}
<nav class="navbar navbar-dark background-dark">
<h1 class="navbar-brand">
<div *ngIf="noInternetConnection; then offlineBlock; else onlineBlock"></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