Tuesday, July 31, 2018

Using Lodash in Typescript and Angular 6 applications with example

Lodash Integration with Angular 5 introduction

Lodash integration with angular/typescript example

As we already discussed lodash library in my previous article. This article covers steps to integrate into an Angular application.
We need certain steps to integrate third-party libraries into Angular applications.
with this, You are able to use utility functions in angular projects.

I am going to explain about the existing application which is generated an application using angular cli code generator tool. The below steps will work on all Angular 4/5/6 versions.
Now go to the project directory and install the lodash library.

Install and setup lodash

Lodash has provided npm and yarn installer. First, install in your project using below command based on your package manager
npm install --save lodash or 
yarn add lodash
This creates following entry in package.json
"dependencies": {
    "lodash": "^4.17.10",
And also lodash dependencies installed into your projectdirectory/node_modules/lodash folder.

Install types/lodash definition file

Next step is to Configure typescript definition file Lodash is a javascript library and Angular is based on typescripts. So you need to provide typescript definition files. The extension of This file always ends with d.ts. This file contains type checking information of javascript objects. package for typing is @types/lodash. if you don't know typing information for a specific library, you can check Microsoft typing tool
npm install --save @types/lodash
yarn add @types/lodash
Once lodash and typing definition file is installed successfully, You need to do code changes as below.

Component lodash changes

You don't need any code changes at the module level, instead, you can do changes in your component. Instead of the component, the Best way is to write a utility service which is a wrapper for this module. so that components and module are loosely coupled. For now, I am giving example for component usage.
import * as _ from 'lodash';
export class AppComonent implements OnInit {
  ngOnInit() {
    console.log(_.isEmpty({})); // returns true
import keyword import all classes and methods from the module into this component. Now you can able to call any function on Underscore ie _.functionName


Note: Only a member of this blog may post a comment.