How to implement Lodash in Angular 12 .?

Lodash is an open-source JavaScript utility library delivering consistency, modularity, performance, & extras. Lodash helps programmers to write more concise and maintainable JavaScript. In these articles, we’ll learn how to install Lodash properly in angular and demonstrate some lodash library functions in Angular.

In this article, we will learn how to use the Lodash library in Angular and we have demonstrated a few examples of how to use Lodash in Angular.

Why use Lodash in Angular?

Lodash library can be used at front-end and back-end like node js. This makes Lodash ubiquitous whenever there are Javascript technologies we can use Lodash. Angular used typescript and which intern needs to convert to Javascript at the end. We can easily use Lodash in Angular. Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash library can be broken down into several categories. Lodash’s modular methods are great for:

  • Creating composite functions
  • Iterating arrays, objects, & strings
  • Manipulating & testing values

Lodash has several built-in utility functions and makes developer life easier by making our code small and easy to maintain. Instead of writing our own functions, again and again, we can accomplish with a single line of code.

Prerequisites:
To create and run an Angular project, We need nodejs and Angular CLI already install in our system, if not then check how to install nodejs and angular in Ubuntu. To install the Angular CLI, open a terminal and run the following command:

npm install -g @angular/cli

How to install Lodash in Angular

Let first create an Angular project, where we demonstrate some of the most useful methods of Lodash in our Angular project.

ng new lodashAngular
npm install lodash --save

Running the above command will create an Angular Lodash project and Lodash is ready to use in our project, but it’s just the raw library. What we also need is the type definitions to give us strongly typed definitions inside typescript. For that, we need to install one more package.

npm install @types/lodash --save-dev

Note that we only add the type definitions as a dev dependency as it is not required at runtime, only while you are developing your project.

Angular Lodash example using different methods of Lodash library

We have installed all the required libraries in our Angular project to use Lodash in Angular. We can now Lodash method anywhere in our Angular project. We will demonstrate some of the most popular Lodash methods in our Angular project.

Angular lodash example
Angular Loadsh example

Import Lodash in our Angular project

Now we can import the Angular Lodash method directly into our Angular component. In the app.component.ts typescript file import Lodash. Let’s edit the app.component.ts file to implement Angular Lodash.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  rating = '';
  movieExist: boolean | undefined;
  movieNotExist: boolean | undefined;

  movies = [
    { name: 'Batman Begins', rating: 8.2 },
    { name: 'Insomnia', rating: 7.1 },
    { name: 'Doodlebug', rating: 7.1 },
    { name: 'Test', rating: 2 }
  ];

  names = ['Angular', 'Ionic', 'React', 'Vue', 'Fluter'];
  moviesByRating: any;
  removeName: any;
  sortedNums = [11, 13, 21, 3, 3, 15, 18, 8, 13];


  constructor() { }

  ngOnInit() {
    this.movieExist = !!_.find(this.movies, { name: 'Batman Begins' });
    this.movieNotExist = !!_.find(this.movies, { name: 'ABABAB' });
    // Also possible to filter array object by find
    const findValue = _.find(this.movies, (movie) => movie.rating = 7.1);

    // lodash times
    console.log(_.times(3, String)); //  ['0', '1', '2']
    console.log(_.times(2, _.constant('edupala')));['edupala', 'edupala']

    //Lodash Sets the value at path of object. No path
    // in our case add Bootstrap at end of names array
    _.set(this.names, '4', 'Bootstrap');
    console.log(this.names);

    // Lodash clone function
    const copy = _.cloneDeep(this.movies);
    console.log('This copy method of lodash : ' + copy);

    // Lodash sortedUniq remove duplicate and sort
    console.log('Sort and remove duplicate', _.sortedUniq(this.sortedNums));

    // Lodash debouce // delay calling 5000 second
    _.debounce(this.callMethods, 5000)();
  }

  //Lodash filter function
  findMoviesByRating(rating: number): void {
    this.moviesByRating = _.filter(this.movies, (movie) => movie.rating > rating);
  }

  //Lodash pull to remove item from array
  removeItem(item: string): void {
    this.names = _.pull(this.names, item);
    console.log(this.names);
  }

  // Lodash sort
  sortAscendingMovies() {
    this.movies = _.sortBy(this.movies, 'name');
  }

  // Lodash reverse
  sortDescendingMovies() {
    this.movies = _.sortBy(this.movies, 'name').reverse();
  }

  callMethods(): void {
    alert('Call after 5 second');
  }
}


Edit the app.component.html template

<div class="container">
  <h3 style="color: blue">Implementing Lodash in Angular</h3>
  <div>
    <h4>1. Lodash find function: </h4>
    Does movie Batman Begin exist in movies list by Lodash find : <b>{{ movieExist }}</b>
    <p>
      Does movie ABABAB exist in movies list by Lodash find : <b>{{ movieNotExist }}</b>
    </p>
  </div>

  <form>
    <h4>2. Lodash filter function:</h4>
    <label>Find movies by rating[1 to 10] more than </label><br />
    <input name="rating" [(ngModel)]="rating" #ratingCtrl="ngModel">
    <button (click)="findMoviesByRating(ratingCtrl.value)">Find movies</button>
  </form>

  <div *ngFor="let movie of moviesByRating">
    {{ movie.name }} - {{ movie.rating }}
  </div><br />

  <div>
    <h4>3. Lodash pull function:</h4>
    <label>Select movie to remove using lodash pull methods:</label>
    <select name="removeName" [(ngModel)]="removeName" #removeCtrl="ngModel">
      <option *ngFor="let item of names"> {{ item }} </option>
    </select>
    <button (click)="removeItem(removeCtrl.value)">Remove Item</button>
  </div>

  <div>
    <h4>4. Lodash sort function:</h4>
    <ol>
      <li *ngFor="let movie of movies">
        {{ movie.name }} - {{ movie.rating }}
      </li>
    </ol>

    <button type="button" class="btn btn-primary" (click)="sortAscendingMovies()">Sort Movies Ascending</button>
    <button type="button" class="btn btn-primary" (click)="sortDescendingMovies()">Sort Movies Ascending</button>
  </div>

</div>

<router-outlet></router-outlet>

Angular Lodash functions

The Lodash library has lots of functions and is also categorized into different functionalities. Here we have listed a few functions and their description.

includes function:
The _.includes() method is used to find the value is in the collection or not. If the collection is a string, it will be tested for a value sub-string, otherwise, SameValueZero() method is used for equality comparisons. We will demonstrate how to use Lodash include a function to check the file type of images.

selectImage(event) {
    this.file = event.dataTransfer ? event.dataTransfer.files[0]:event.target.files[0];
    
      const allowed_types = ['image/png', 'image/jpeg', 'image/jpg'];

    if (!_.includes(allowed_types, this.file.type)) {
      console.log('Invalid image format, please select a valid image format');
      return false;
    }
    
    ....
 }

filter function:
It will return a new array that contains all matching occurrences. In our case, we have an input field, when the user types the rating it will filter all movies which have a rating more than the type value in the input.

find function
find iterates over elements of the collection, returning the first element predicate returns truthy for.

pull function
Remove all given values from an array. We have a select option, where once the user selects an item and clicks on the remove button will invoke the pull function to remove the selected item from an array.

times function
Invokes the iterate n times, returning an array of the results of each invocation. The iterate is invoked with one argument.

debounce function
debounce function will delay invoking function for a specified time in debounce function.

sortBy function
Creates an array of elements, sorted in ascending order by the results of running each element in a collection through each iteration.

_.sortedUniq function
This method is like _.uniq except that it’s designed and optimized for sorted arrays.

Conclusion
We have completed our Angular lodash example and we have demonstrated some of the most popular Lodash methods in our angular project.

Related posts

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top