Skip to content

Latest commit

 

History

History
93 lines (67 loc) · 2.95 KB

README.md

File metadata and controls

93 lines (67 loc) · 2.95 KB

🔭 @ultimate/ngx-pagevisibility

Angular Directive that implements the Page Visibility API.



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 a NgxPageVisibilityState object on every visibilitychange event
  • visible$: Emits a NgxPageVisibilityState object when the document is visible
  • hidden$: Emits a NgxPageVisibilityState 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>