For enquiries call:

Phone

+1-469-442-0620

Aage ki Socho

HomeBlogWeb DevelopmentHow to Build a Library for Angular Apps? [Step-by-Step Guide]

How to Build a Library for Angular Apps? [Step-by-Step Guide]

Published
14th Feb, 2024
Views
view count loader
Read it in
10 Mins
In this article
    How to Build a Library for Angular Apps? [Step-by-Step Guide]

    Have you ever played with Legos? Imagine building a Lego structure. You have all the necessary bricks, but something's missing. Maybe you need a specific shape or piece that isn't available in the current set. But wait! You can actually create your custom brick to fill that gap and make your structure even more unique. 

    Similar is the case when working with Angular; you might encounter situations where you need some reusable components, handy services, or specific functionalities that aren't readily available. But you can build your own Angular libraries to fill those gaps and even share them with the world. Sounds exciting, right? Think of it as a special Lego brick containing all the essential code you need, ready to use in your project. In this blog, I’ll take you through a step-by-step guide on creating, building, and using the Angular library.

    In this article, we are going to talk about Libraries in Angular 13 and how to build a library for angular apps.  We will be covering the following topics in the blog:

    • Reusability with Angular Libraries:
      • Here we introduce the idea of reusability and the concept of building libraries in Angular apps.
    • Creating a New Library:
      • Here we will walk through steps to generate a new library using the ng generate.
    • Rebuilding an app using libraries:
      • Here we walk through an example where we convert a portion of an existing Angular 13 app to a library and then use it.
    • Publishing your library:
      • Here we walk through publishing a library, keeping Ivy-related features, version compatibility etc. in mind.
    • Summary

    What is Angular Library? 

    A library is a collection of precompiled routines that a program can use. Similarly, Angular libraries serve as modular sets of code that enable the encapsulation and reuse of functionality across diverse Angular projects. In other words, Angular libraries are crucial tools for developers seeking to enhance code organization, maintainability, and reusability in Angular projects. 

    About Angular 13

    Angular 13 is the latest version of the Angular family. Angular applications are basically designed for single-page applications, where all controls are required in single-page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated Single Page Applications (SPAs). These SPAs are efficient enough to give us a component to view the model environment, making it an MVC or MVVM application.

    Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App-like experience with high performance. Angular has zero-step installation, making its up-gradation using modern web capabilities possible, even if offline. Angular has the capability of making a cross-platform Desktop App that can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP, and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command-Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable. Check out the Full Stack Developer online course for more information. Know more about angular cli.

    According to angular.io, some of the features worth mentioning are:

    1. DEVELOP ACROSS ALL PLATFORMS

    • Learn one way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web, mobile web, native mobile, and native desktop.  

    2. SPEED & PERFORMANCE

    • Achieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.
    • Angular puts you in control over scalability. Meet huge data requirements by building data models on RxJS, Immutable.js, or another push model.

    3. INCREDIBLE TOOLING

    • Build features quickly with simple, declarative templates. Extend the template language with your own components and use a wide array of existing components.  
    • Get immediate Angular-specific help and feedback with nearly every IDE and editor. All this comes together so you can focus on building amazing apps rather than trying to make the code work.

    4. LOVED BY MILLIONS

    • From prototype through global deployment, Angular delivers the productivity and scalable infrastructure that supports Google's largest applications.

    Reusability with Angular Libraries

    A Library in Angular App is a reusable code that determines Angular components, services, or projects meant to be called by other projects. These projects are like a normal application. The only difference these have over Angular applications is that these projects cannot execute on their own. We need to import these projects to use them.

    We make libraries to solve some generic issues like the unified user interface or data presentation or data entry issues. Angular developers create these libraries for such general-purpose solutions. Later these libraries can be adapted in different applications for re-usage of the solution.

    An Angular Library can be built as an Angular application, later published as an npm package. These npm packages can be shared with different applications deploying the libraries.

    Libraries can be published as third-party libraries or Angular Team libraries.

    Some of the examples are:

    1. ReactiveFormsModule from the @angular/forms library is used to add reactive forms to an Angular app. We add this library package by using ng add @angular/forms and then importing the ReactiveFormsModule from the @angular/forms.
    2. To turn an Angular App into a progressive application we add the service worker library. This turns our code into a Progressive Web App (PWA).
    3. A very large and general-purpose library is the Angular Material. It is a library or a component that helps in constructing attractive, sophisticated, functional web app and reusable, and adaptable UI components.

    To advance your career in web development, enroll in a learning Web Development course.   

    Creating a New Library

    Let us build a Library in Angular App step-by-step:

    Step 1: Install Node.js:

    • Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.
      • The latest Version is: node-v16.13.1-x64
    • Install node.js once downloaded:

    How to Create Libraries for Angular Apps?

    How to Create Libraries for Angular Apps?

    • Once you have installed Node.js on your system, open node.js command prompt.
    • To check your version, run node -v in a terminal/console window.

    How to Create Libraries for Angular Apps?

    Step 2: Use npm to Install Angular CLI

    • Use the following command to install Angular CLI
    npm install -g @angular/cli  

    Or

    npm install -g @angular/cli@latest

    How to Create Libraries for Angular Apps?

    Or

    • Just go to Angular CLI official website Angular.io.
    • You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are the same for Windows and Mac.

    How to Create Libraries for Angular Apps?

    • To check Node and Angular CLI version, use ng --version command.

    How to Create Libraries for Angular Apps?

    Step 3: Create an app called ngApp4Library

    Syntax:

    ng new app_name
    C:\>ng new ngApp4Library 

    It asks for

    Would you like to add Angular routing? Yes

    Which stylesheet format would you like to use?

    > CSS 

    ….

    How to Create Libraries for Angular Apps?

    How to Create Libraries for Angular Apps?

    Step 4: Generate Library via CLI:

    Syntax: for creating a Library

    ng generate library <name> [options]
    ng g library <name> [options]
    • Let us generate the required library: here we are going to create “my-lib” Library.
    • Go to the app folder and install the required Library: “my-lib”:

    ng generate library my-lb

    How to Create Libraries for Angular Apps?

    • This will create a library project my-lib into our ngApp4library project.
    • my-lib Library will contain library module, services, components, etc.

    How to Create Libraries for Angular Apps?

    Step 5: Edit the library ts file: Give a functionality to your library

    As you can see our library has its own module, service, and component. We can add more components, services, directives, pipes, and modules as per our needs.

    The Library file that we need to edit is my-lib. It appears in the folder C:\Users\ISHU\Desktop -> ngApp4Library -> projects -> my-lib -> src -> lib. The file to be edited is:  my-lib.component.ts

    Add the following code:

    import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'lib-my-lib',
      template: `
    <form  method="post">
      <div >
        <label for = "username"> <b> Username: </b> </label>
        <input type = "text" placeholder = "Enter Username here" name = "username" style = "margin:10px;" required>
      <br/>
        <label for = "passwd"> <b> Password: </b> </label>
        <input type = "password" placeholder = "Enter Password here" name = "passwd" style = "margin:10px;" required>
      <br/>
         <button type = "submit"> Login </button>
    </div>
    </form>
      `,
      styles: [
      ]
    })
    export class MyLibComponent implements OnInit {
      constructor() { }
      ngOnInit(): void {
      }
    }

    Rebuilding an app using libraries

    1. Before consuming the library, we need to build an Angular library.
    2. Here we will build the library for local (same application) usage.
    3. Then we will re-build the library for global (any application) usage.

    Creating a New Library

    1. Build the library and consume it in the same application:

    • To build the library, we run the following command:
    ng build <library name>
    • Here our library name is my-lib, thus the command we need is: ng build my-lib

    How to Create Libraries for Angular Apps?

    • The command will generate the library dist folder
    • Next step is to implement the library into our current project: ngApp4Library:
    • For this step, we need to import this library in our main app (ngApp4Library).
    • In app.module.ts import my-lib library module as shown: app.module.ts:
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { MyLibModule } from 'my-lib';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        MyLibModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    • Now, we simply add the my-lib library in the HTML file.
    • Please note that the selector for the library used here is: lib-my-lib
    • To know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.ts
    • Now open and edit: app.component.html from the main App folder: ngApp4Library\src\app\ app.component.html: 
    <lib-my-lib></lib-my-lib>

    How to Create Libraries for Angular Apps?

    • Now we can start our application from the Node.js command line as: ng serve

    How to Create Libraries for Angular Apps?

    • Open the favourite browser and type the default Angular app URL to check the output: localhost:4200/.

    How to Create Libraries for Angular Apps?

    2. Rebuild the library and consume it from some other application:

    We go through the following steps to implement the Library into another project:

    Step 1:

    • To Re-build the library, we run the following command:
    ng build <library name>
    • Here our library name is my-lib, thus the command we need is: ng build my-lib

    How to Create Libraries for Angular Apps?

    • The command will generate the library dist folder
    • Now, create a new Angular application: ngAppClient in a new command window. We need to let the library application run.
    ng new ngAppClient

    How to Create Libraries for Angular Apps?

    • Now from the build, check the paths destined as “to”

    How to Create Libraries for Angular Apps?

    • Here, the “to” part gives us the value: C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-lib
    • So, now copy this path: “C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-lib”
    • Next, we open the terminal of ngAppClient project and install this library with the following command into the ngAppClient project: 
      • npm i C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-lib
      • C:\Users\ISHU\Desktop>cd ngAppClient
      • C:\Users\ISHU\Desktop\ngAppClient>npm i
      • C:\Users\ISHU\Desktop\ngApp4Library\dist\my-lib

    How to Create Libraries for Angular Apps?

    • After installation of the library in the client application, we can import the library into the app.module.ts of the client app. After importing the library module, we can easily use those services, components, etc.
    • To use the library:
      • Open Client Project -> app.module.ts file and edit it to add the library:

    App.module.ts:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { MyLibModule } from 'my-lib';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        MyLibModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    • Now, we simply add the my-lib library in the client project app.component.html file.
    • Please note that the selector for the library used here is: lib-my-lib
    • To know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.ts
    • And then open and edit: app.component.html from the client App folder: ngAppClient\ src\ app\ app.component.html:
    <lib-my-lib></lib-my-lib>
    

    How to Create Libraries for Angular Apps?

    • We can now start our client application for the Node.js command line as:
    ng serve.
    • In case the Library project is running in the default port, 4200, we can change the port of the client app to 5200 by the following command:
    ng serve --port 5200

    How to Create Libraries for Angular Apps?

    • Open your favorite browser and type the default Angular app URL to check the output: localhost:5200/.

    How to Create Libraries for Angular Apps?

    Publishing your library

    We publish the library to make the library available on npm. For publishing the library, all we need to do is create a production build, and then run npm publish command from the library project’s dist directory.

    The Syntax is as follows:

    ng build <library name> --prod
    cd dist/<library name>
    npm publish

    Here the Library project is ngApp4library, and the library is my-lib, so we run the following commands:

    ng build my-lib --prod
    cd dist/my-lib
    npm publish

    If you have not published anything before, you will need to create an npm account first and log in into your npm account and then publish your library.

    Looking to enhance your coding skills? Get certified in Python, the versatile programming language that powers everything from web development to data analysis. Join our Python course certification and unlock endless possibilities. Start your journey today!

    The Purpose of Angular Libraries

    Angular Libraries are very useful in case we want to re-use components, services, modules, etc. in our application. We just need to add the published library in our project, and that’s it, the components, modules, services, are all ready to be used in the application.

    To create a library, we generate it by “ng generate” command, built it by “ng build” command, publish by “npm publish” command. To use a library we install it by “ng i “ command.

    Use Cases for Angular Libraries 

    These libraries are essentially pre-built components, like windows and doors, that you can "plug and play" into your Angular applications. Instead of writing code from scratch, you can simply import existing libraries and use them immediately. 

    Angular libraries find applications in a variety of scenarios, offering benefits such as 

    • Code Reusability: Share common components and services across multiple projects, reducing redundancy. In other words, think about all the common features used across different applications, like navigation bars, login forms, or fancy buttons. Instead of writing these features every time, you can store them in a library and reuse them across projects. It's like having a box of building blocks that you can easily assemble into different creations! 

    • Maintainability: It helps to centralize code updates in the library, making it easier to manage and enhance functionality. Think of it this way, imagine updating a specific feature in multiple projects manually. Sounds like a nightmare, doesn't it? With libraries, you only need to update the code in one place, and the changes automatically apply across all projects using that library. It's like having a remote control for your house, where changing one setting affects all the lights at once! 

    • Collaboration: Building software is often a team effort. By using shared libraries, everyone works with the same components and standards. This promotes consistency and it makes it simpler for different developers to collaborate on the same project. It's like having a shared language that everyone understands, making communication and teamwork quite easy! 

    Here are a few real-world examples where Angular libraries can be beneficial. 

    Example 1: If you're working on multiple Angular projects, and you want to maintain consistency in the UI components across these projects then you can create a shared UI components library. 

    • Step 1: Library creation 
      • $ ng generate library shared-components 
    • Step 2:  Library Usage (In Angular): 

     

    Example 2: Imagine that you have multiple Angular projects that require authentication. You want to maintain a consistent authentication mechanism.  

    • Step 1: Library creation 
      • $ ng generate library auth 
    • Step 2: Library Implementation 


    • Step 3: Library Usage (In Angular): 

     

    Example 3: Let’s say that you want to create a reusable feature module for handling file uploads.  

    • Step 1: Library creation:
      • $ ng generate library file-upload 
    • Step 2: Library Implementation: 


    Step 3: Library Usage (In Angular): 

    Conclusion 

    In conclusion, the to create angular libraries and utilize them are instrumental in building scalable, maintainable, and collaborative projects. Using libraries doesn't just save time and effort; it also improves the quality of your code. Libraries are typically well-tested and documented, ensuring reliability and stability in your applications.  

    This tutorial on how to create a library in Angular helps you with the knowledge to initiate, develop, build, and share Angular libraries effectively. Whether you're an experienced developer or just starting out, Angular Libraries will always be handy. They offer a powerful way to share code, improve maintainability, and make collaboration a breeze. You can embrace the power of Angular libraries to streamline your development process, enhance code quality, and contribute to the robust Angular ecosystem. Happy coding! 

    Frequently Asked Questions (FAQs)

    1. What is the purpose of the projects folder in Angular libraries?  

     The "projects" folder in an Angular library is like the engine room of the whole operation. Think of it as the tool drawer in the kitchen which contains all the necessary tools, similarly, the "projects" folder contains different projects for specific purposes: 

    • Library Project: This is the main attraction, housing the actual code for your components, services, modules, and more. 
    • Test Project: This project plays the role of a quality control team. It holds unit tests that check if your library code works as intended, ensuring everything is in tip-top shape. 
    • E2E Project: This project is like the test kitchen where you try out your creations. It simulates how real users would interact with your library and makes sure it functions smoothly in real-world scenarios. 

    All of these projects work together in harmony to build something amazing. You can also say that the “projects folder is the powerhouse where your libraries come to life.” 

    2. How can I add components, services, or other features to my Angular library? 

    To add components, services, or other features to your Angular library: 

    First of all choose the feature type (component, service, etc).  Once it is decided you can generate all the necessary files using Angular CLI.  

    Now write the code for your chosen feature. Once you've written your code, you need to export it from its respective module so other parts of your library can access it. Use the export keyword to make your components, services, pipes, directives, or other features available for import. Then import and use your feature in other parts of your library. Use frameworks like Jest or Jasmine to write your unit tests.  

    3. Can I use third-party libraries in my Angular library? 

     Yes, you can use third-party libraries in your angular library. In fact, using third-party libraries in your Angular library can be a great way to save time and effort.  

    There are several advantages as well: 

    • It reduces the code and you can use the existing code from well-written libraries instead of writing everything from scratch. 
    • You can get community support as many popular libraries have large and active communities that you can tap into for help and support. 

    However, there are a few things you should keep in mind while using third-party libraries: 

    • Check if the library that you are using is compatible with your angular version and meets your specific requirements. 
    •  You need to carefully manage the dependencies of your library and ensure that they are compatible with the third-party libraries you are using. 
    •  Make sure that the library you are using is well-maintained 
    Profile

    Monica Gupta

    Author

    I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon