Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ngx-lottie

Package Overview
Dependencies
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ngx-lottie

  • 5.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
84K
increased by2.57%
Maintainers
1
Weekly downloads
 
Created
Source

A minimal customizable performance-stable Angular component for rendering After Effects animations. Compatible with Angular 8+ and Ivy renderer.

Build status Licence: MIT npm version David

Table of contents

Features

  • rich: ngx-lottie provides more opportunities to work with API exposed by Lottie
  • strict: all types of objects and events are available to you
  • performant: the lottie-web library can be loaded synchronously or on demand

Quick example

<ng-lottie
  width="600"
  height="500"
  containerClass="moving-box"
  [styles]="styles"
  [options]="options"
  (animationCreated)="animationCreated($event)"
  (configReady)="configReady()"
  (dataReady)="dataReady()"
  (domLoaded)="domLoaded()"
  (enterFrame)="enterFrame($event)"
  (segmentStart)="segmentStart($event)"
  (complete)="complete($event)"
  (loopComplete)="loopComplete($event)"
  (destroy)="destroy($event)"
  (error)="error($event)"
></ng-lottie>

Installation

To install ngx-lottie run the following command:

npm i lottie-web ngx-lottie
# Or if you use yarn
yarn add lottie-web ngx-lottie

Usage

First, import the LottieModule into AppModule:

import { NgModule } from '@angular/core';
import { LottieModule } from 'ngx-lottie';
import player from 'lottie-web';

// Note we need a separate function as it's required
// by the AOT compiler
export function playerFactory() {
  return player;
}

@NgModule({
  imports: [
    LottieModule.forRoot({ player: playerFactory })
  ]
})
export class AppModule {}

The lottie-web library can be loaded on demand using dynamic import. Given the following code:

import { NgModule } from '@angular/core';
import { LottieModule } from 'ngx-lottie';

export function playerFactory() {
  return import('lottie-web');
}

@NgModule({
  imports: [
    LottieModule.forRoot({ player: playerFactory })
  ]
})
export class AppModule {}

Now you can simply use the ng-lottie component and provide your custom options via the options binding:

import { Component } from '@angular/core';
import { AnimationItem } from 'lottie-web';
import { AnimationOptions } from 'ngx-lottie';

@Component({
  selector: 'app-root',
  template: `
    <ng-lottie
      [options]="options"
      (animationCreated)="animationCreated($event)"
    ></ng-lottie>
  `
})
export class AppComponent {
  options: AnimationOptions = {
    path: '/assets/animation.json'
  };

  animationCreated(animationItem: AnimationItem): void {
    console.log(animationItem);
  }
}

Also it's possible to use the lottie directive if you'd like to provide your own custom container and control it:

import { Component } from '@angular/core';
import { AnimationItem } from 'lottie-web';
import { AnimationOptions } from 'ngx-lottie';

@Component({
  selector: 'app-root',
  template: `
    <main
      lottie
      [options]="options"
      (animationCreated)="animationCreated($event)"
    ></main>
  `
})
export class AppComponent {
  options: AnimationOptions = {
    path: '/assets/animation.json'
  };

  animationCreated(animationItem: AnimationItem): void {
    console.log(animationItem);
  }
}

Notice that you will need to import the LottieModule into other modules as it exports ng-lottie component and lottie directive. But forRoot has to be called only once!

Caching

lottie-web will load your JSON file every time when animation is being created. When importing LottieModule into the root module you can provide the useCache option:

import { NgModule } from '@angular/core';
import { LottieModule } from 'ngx-lottie';

export function playerFactory() {
  return import('lottie-web');
}

@NgModule({
  imports: [
    LottieModule.forRoot({
      player: playerFactory,
      useCache: true
    })
  ]
})
export class AppModule {}

This will enable cache under the hood. Since the cache is enabled your JSON file will be loaded only once.

API

Bindings

The ng-lottie component supports the following bindings:

@Component({
  selector: 'app-root',
  template: `
    <ng-lottie
      width="500"
      height="600"
      containerClass="moving-box"
      [styles]="styles"
      [options]="options"
    ></ng-lottie>
  `
})
export class AppComponent {
  options: AnimationOptions = {
    path: '/assets/animation.json'
  };

  styles: Partial<CSSStyleDeclaration> = {
    maxWidth: '500px'
  };
}
  • options: AnimationOptions options used by AnimationItem
  • width?: string container element width in pixels. Bound to [style.width.px]
  • height?: string container element height in pixels. Bound to [style.height.px]
  • styles?: Partial<CSSStyleDeclaration> custom styles object. Bound to [ngStyle]
  • containerClass?: string custom container class. Bound to element

The lottie directive supports only options binding.

Events

@Output()TypeRequiredDescription
animationCreatedAnimationItemoptionalDispatched after the lottie successfully creates animation
configReadyvoidoptionalDispatched after the needed renderer is configured
dataReadyvoidoptionalDispatched when all parts of the animation have been loaded
domLoadedvoidoptionalDispatched when elements have been added to the DOM
enterFrameBMEnterFrameEventoptionalDispatched after entering the new frame
segmentStartBMSegmentStartEventoptionalDispatched when the new segment is adjusted
loopCompleteBMCompleteLoopEventoptionalDispatched after completing frame loop
completeBMCompleteEventoptionalDispatched after completing the last frame
destroyBMDestroyEventoptionalDispatched in the ngOnDestroy hook of the service that manages lottie's events, it's useful for releasing resources
errorBMRenderFrameErrorEvent OR BMConfigErrorEventoptionalDispatched if the lottie player could not render some frame or parse the config

Optimizations

The ng-lottie component is marked with OnPush change detection strategy. This means it will not be checked in any phase of the change detection mechanism until you change the reference to some binding. For example if you use an svg renderer and there are a lot DOM elements projected — you would like to avoid checking this component, as it's not necessary.

Also AnimationItem events are listened outside of the Angular's zone. Thus you shouldn't worry that Lottie's events will cause the ApplicationRef to invoke tick every ms.

Server side rendering

⚠️ Warning: This works only if Ivy is NOT enabled! Ivy doesn't work with SSR right now and probably will be supported in Angular 10.

By default, lottie will load your json file with animation data every time you create an animation. You may have some problems with the connection, so there may be some delay or even timeout. It's worth loading animation data only once and cache it on the client side, so every time you create an animation — the animation data will be retrieved from cache.

ngx-lottie/server package gives you the opportunity to preload animation data and cache it using TransferState.

How2?

TL;DR - see integration folder.

Import the LottieServerModule into your AppServerModule:

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { LottieServerModule } from 'ngx-lottie/server';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    // `AppModule` first as you know
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    LottieServerModule.forRoot({
      preloadAnimations: {
        folder: 'dist/assets',
        animations: ['data.json']
      }
    })
  ],
  bootstrap: [AppComponent]
})
export class AppServerModule {}

Don't forget to import BrowserTransferStateModule into your AppModule. Let's look at these options. animations is an array of json files, that contain animation data, that should be read on the server side, cached and transfered on the client. folder is a path where your json files are located, but you should use it properly, this path is joined with the process.cwd(). Imagine such project structure:

— dist (here you store your output artifacts)
  — project-name
    — assets
    — index.html
    — main.hash.js
— dist-server
  — server.js
— src (here is your app)
— angular.json
— package.json
— webpack.config.js

If you start a server from the root folder like node dist-server/server, thus the folder property should equal dist/project-name/assets.

After installing LottieServerModule - now you have to import LottieTransferState from the ngx-lottie package. Don't worry, this service is tree-shakable and won't be bundled if you don't inject it anywhere.

Inject this service into your component where you declare animation options:

import { Component } from '@angular/core';
import { AnimationOptions, LottieTransferState } from 'ngx-lottie';

@Component({
  selector: 'app-root',
  template: `
    <ng-lottie [options]="options"></ng-lottie>
  `
})
export class AppComponent {
  options: AnimationOptions = {
    animationData: this.lottieTransferState.get('data.json')
  };

  constructor(private lottieTransferState: LottieTransferState) {}
}

Notice, data.json is a filename that you pass to the preloadAnimations.animations property. Finally change this:

platformBrowserDynamic().bootstrapModule(AppModule);

To this:

document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic().bootstrapModule(AppModule);
});

Keywords

FAQs

Package last updated on 05 Oct 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc