How to create angular library using Angular 12 - part 1

Step 1: Install angular cli

Install the CLI using the npm package manager.

npm install -g @angular/cli

Step 2: Create the workspace

Use the Angular CLI to generate a new workspace with the following commands.

ng new my-workspace --create-application=false --interactive=false

--create-application=false parameter avoids the creation of an initial application (default value is true). Otherwise, the Angular CLI creates an application in the src folder of the new workspace. It’s cleaner to generate all applications in the sub-folder projects of the workspace.

--interactive=false parameter is just here to avoid being prompted for useless parameter values such as whether the initial app (which we don’t generate) should include a routing module or what CSS preprocessor to use.

work space creation

Once created the workspace, then change the directory by following command.

cd my-workspace

Step 3: Create a Library

The ng generate library <library-name>command is used to generate library.

ng generate library my-lib

added library to work space
Library folder structure
tsconfig.json updated after library created

Step 4: Create an Application

The ng generate application <application-name> command is used to generate application.

ng generate application my-app

Added application to work space
Application folder structure

To serve an application, run the following command.

ng serve --project=my-app

Serve an application

To build the library, run the following command.

ng build --project=my-lib

After build successful, we can get 2 paths.

After build library- Dist folder path

Step 5: Implement library into application

Import the library module to app module.

app.module.ts after import MyLibModule

After importing the module in app.module, Need to add the library component selector tag in app.component.html. We can find the selector tag in the file projects/my-lib/src/lib/my-lib.component.ts, where you can get selector inside @component decorator.

app.component.html
Launch the application

Step 6: Test Library in angular production environment

To build the production application use the following command.

ng build --project=my-app

After successful build, my-app folder will get created in dist folder.

Dist folder

To run the angular production build follow the below steps.

  1. Install the http-server globally.

npm install http-server -g

2. Run the angular production build.

http-server dist/my-app

http-server running

To launch the angular production application in any of the above available URL’s.

In part 2 we will see about angular pipe’s

Source Code

Download here

Senior Software Developer