We all might be familiar with the JavaScript way of checking Online/ Offline status. But in the case of Angular, we need to duly unsubscribe the events we're harkening to, else, we might beget gratuitous actions and memory leaks.
Plain JavaScript
window.addEventListener("load", () => {
this.internetStatus = navigator.onLine
window.addEventListener("online", () => {
this.internetStatus = true
});
window.addEventListener("offline", () => {
this.internetStatus = false
});
});
Angular
- app.component.html
<h1>Internet Status</h1>
<div
class="widget-content-online header-user-info ml-3"
*ngIf="internetStatus"
>
● Online
</div>
<div
class="widget-content-offline header-user-info ml-3"
*ngIf="!internetStatus"
>
● Offline
</div>
- app.component.ts
import { Component, OnDestroy, OnInit, VERSION } from '@angular/core';
import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
internetStatus: boolean = false;
internetStatus$: Subscription = Subscription.EMPTY;
constructor() {}
ngOnInit(): void {
this.checkInternetStatus();
}
ngOnDestroy(): void {
this.internetStatus$.unsubscribe();
}
checkInternetStatus() {
this.internetStatus = navigator.onLine;
this.internetStatus$ = merge(
of(null),
fromEvent(window, 'online'),
fromEvent(window, 'offline')
)
.pipe(map(() => navigator.onLine))
.subscribe(status => {
console.log('status', status);
this.internetStatus = status;
});
}
}
- styles.css
.widget-content-online {
padding: 3px 11px 5px 11px;
border-radius: 52px;
width: 90px;
background: rgba(67, 164, 90, 0.15);
font-size: 15px;
color: #43A45A;
text-align: center;
}
.widget-content-offline {
padding: 3px 11px 5px 11px;
border-radius: 52px;
width: 90px;
background: rgba(165, 83, 83, 0.15);
font-size: 15px;
color: #e52525;
text-align: center;
}
Here you can see the Demo: https://check-online-offline-status-in-angular.stackblitz.io
Here you check the code: https://github.com/glokesh94/check-online-offline-status-in-angular
Follow on youtube channel for more videos: Youtube Channel
Here you can see youtube video: Detect network connection is Online/Offline Status Using Angular