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
|
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