Using lodash in Angular 4

Importing lodash or any javascript library inside angular:

step-1: Install the libarary(lodash)

npm i --save lodash

step-2: import it inside the component and use it.

import it as follow:

import 'lodash';

declare var _:any;

or

import * as _ from 'lodash';

Step-3: Install type definitions for Lo-Dash (it's optional)

npm install --save-dev @types/lodash

see the example if you still have doubts

import { Component, OnInit } from '@angular/core';
// import * as _ from 'lodash';
import 'lodash';

declare var _:any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'test-lodash';

  ngOnInit() {
    console.log(_.chunk(['a', 'b', 'c', 'd'], 2)); //lodash function
    console.log(_.indexOf([1, 2, 1, 2], 2)); //lodash function
  }

}

First you need to install the packages lodash and @types/lodash (contains type definitions):

npm i lodash
npm i --save-dev @types/lodash

Then you can use lodash e.g. with import * as _ from 'lodash'; and further do _.indexOf([1, 2, 1, 2], 2);

You could also do import * as _isEmpty from 'lodash/isEmpty'; (thanks to joshrathke) or import {isEmpty} from 'lodash';

Tags:

Lodash

Angular