Skip to content

Collection of classes and directives for Angular using IntersectionObserver

Notifications You must be signed in to change notification settings

mralexandernickel/ngx-intersection

Repository files navigation

Build Status Coverage Status npm version

ngx-intersection

Events

  • before start ("100px", 0.0)
  • start ("0px", 0.0)
  • after start ("-100px", 0.0)
  • before end ("100px", 1.0)
  • end ("0px", 1.0)
  • after end ("-100px", 1.0)

Needed polyfills

Because the IntersectionObserver is not supported in MS Edge < 15, you need to add a polyfill for it. We cannot import it here directly, because

  1. We do not know if you want to support these browsers
  2. If we do so, we'd break support for serverside rendering

This is why we decided to let the polyfill-responsibility up to you. An easy way to do this would be installing the npm-package intersection-observer by executing:

npm install intersection-observer

or if you use yarn

yarn add intersection-observer

and finally just import the whole package into your polyfills.ts:

import 'intersection-observer';

InjectionTokens

To be able to configure the behavior of the underlying IntersectionObservers, we are providing 5 different InjectionTokens. With these you can set the rootMargins and the thresholds of the IntersectionObserver-Services.

Available InjectionTokens to customize the root-margins are:

  • ROOT_MARGIN_PAST
  • ROOT_MARGIN_PRESENT
  • ROOT_MARGIN_FUTURE

Available InjectionTokens to customize the thresholds are:

  • THRESHOLD_START
  • THRESHOLD_END

To override one (or more) InjectionTokens, you can simply define the provider inside your NgModule:

import {
  ROOT_MARGIN_FUTURE,
  THRESHOLD_END
} from '@mralexandernickel/ngx-intersection';

@NgModule({
  // ...
  providers: [
    {
      provide: ROOT_MARGIN_FUTURE,
      useValue: '120px'
    },
    {
      provide: THRESHOLD_END,
      useValue: 0.75
    },
  ]
})

Allowed Values for root-margins is everything that is also allowed as CSS margin property.

Allowed values for threshold is every number beween 0.0 and 1.0.

More Information can be found on MDN: IntersectionObserver Docs

Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Code scaffolding

Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.

Build

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

Running unit tests

Run ng test to execute the unit tests via Karma.

Running end-to-end tests

Run ng e2e to execute the end-to-end tests via Protractor.

Further help

To get more help on the Angular CLI use ng help or go check out the Angular CLI README.