Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to implement Lodash in Angular 13 |14.?

Angular lodash example

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 is Lodash and how to use it in Angular?

Lodash library can be used at the 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 this 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’s 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 we can use 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');
  }
}

We are using a form, we also need to import FormsModule inside the app.module.ts file as below.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Edit the app.component.html template and let display our Angular Lodash example

<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 item 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>

Lodash functions example in Angular

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

  1. includes function:
    The _.includes() method is used to find whether a 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 the include() 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;
    }
    
    ....
 }

2. 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.

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

4. 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.

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

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

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

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

9. _.mapKeys()
The method is used to create an object with the same values as the object and the keys created by running each of the object’s own enumerable string keys.

const countries = [
 { id: 1, country: 'India'},
 { id: 2, country: 'France'},
 { id: 1, country: 'USA'}
 ];
 
 _mapKeys(countries, 'id')

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

How to implement Lodash in Angular 13 |14.?

One thought on “How to implement Lodash in Angular 13 |14.?

Leave a Reply

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

Scroll to top