@ultimate/ngx-pagevisibility
v0.0.1
Published
<h1 align="center"> 🔭 @ultimate/ngx-pagevisibility </h1> <h4 align="center"> <img width="25" valign="middle" src="https://angular.io/assets/images/logos/angular/angular.svg"> Angular Directive that implements the <a href="https://developer.mozilla.or
Downloads
99
Readme
Installation
Install via npm i @ultimate/ngx-pagevisibility
and register the NgxPageVisibilityModule
into an @NgModule
.
Live Demo
Check the StackBlitz demo and the example code.
Observable API
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
.
Directive API
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>