Angular Directive that implements the Page Visibility API.
Install via npm i @ultimate/ngx-pagevisibility
and register the NgxPageVisibilityModule
into an @NgModule
.
Check the StackBlitz demo and the example code.
Use the NgxPageVisibilityService
and subscribe to any of 3 Observable(s):
changes$
: Emits aNgxPageVisibilityState
object on everyvisibilitychange
eventvisible$
: Emits aNgxPageVisibilityState
object when the document is visiblehidden$
: Emits aNgxPageVisibilityState
object when the document is hidden
The NgxPageVisibilityState
is a simple interface that describes the status of the document visibility:
export interface NgxPageVisibilityState {
visible: boolean
}
Inject the NgxPageVisibilityService
into a component and subscribe.
For the changes$
Observable it may be useful to use the state
to check if you are currently visible
or not.
The state
object is also passed on both visible$
and hidden$
for convenience.
import { NgxPageVisibilityService, NgxPageVisibilityState } from './ngx-pagevisibility.service';
@Component({...})
export class AppComponent implements OnInit {
constructor(private pageVisiblility: NgxPageVisibilityService) {}
ngOnInit() {
// fires on every `visibilitychange`
this.pageVisiblility.changes$
.subscribe((state: NgxPageVisibilityState) => console.log('Change', state.visible));
// fires each time the document is visible
this.pageVisiblility.visible$
.subscribe((state: NgxPageVisibilityState) => console.log('Visible', state.visible));
// fires each time the document is hidden
this.pageVisiblility.hidden$
.subscribe((state: NgxPageVisibilityState) => console.log('Hidden', state.visible));
}
}
Don't forget to unsubscribe
via ngOnDestroy
.
The NgxPageVisibilityDirective
can be declared on an element and listen to the same changes$
, visible$
and hidden$
events:
<div
ngxPageVisibility
(pageVisibilityChange)="onChange($event)"
(pageVisibilityVisible)="onVisible($event)"
(pageVisibilityHidden)="onHidden($event)">
</div>
You can also export the Directive and use the isVisible
boolean property:
<div
ngxPageVisibility
#pagevisibility="ngxPageVisibility">
{{ pagevisibility.isVisible ? 'Visible' : 'Hidden' }}
</div>