Generate your Angular library 📚

Imagine we work in a company where different project teams work on different SPA’s. At the after work 🍺 we tell our colleagues about our impressive alerting library we just implemented today.

They are enthusiastic about our alerting library and want to use it as well. Furthermore, they even think it would be great to make it Open Source so that everybody can benefit from our work. What a great thought!

So the next day we enter the office and start with our library which we call ng-simple-alert .

The first thing we need to do is to create our library project. We open up a terminal of our choice and type the following command which uses the Angular CLI to create a new folder with the basic setup.

In case you have not installed the Angular CLI yet. Go ahead, open a terminal and type npm i -g angular-cli

ng new ng-simple-alert --create-application=false

We explicitly set the --create-application flag to false. Without this flag, the ng new command would generate an application with the same name as the folder, which is not what we want. We want to create a library, not an application.

The result of the execution above is an empty repository. We will now change to this directory and generate our actual library into it.

cd ng-simple-alert

ng generate library ng-simple-alert

We now end up with a library project which is set up under projects/ng-simple-alert .

Show what you got — generate a showcase 🎦

It's a good practice to not only implement your library but also a showcase. The showcase uses the library and gives you an impression of the libraries behavior when a consumer uses it.

In other words; the showcase kinda is your first consumer.

ng generate application ng-alert-showcase

We end up with the following folder structure.

projects

|__ng-simple-alert

|__ng-simple-alert-showcase

|__ng-simple-alert-e2e

We successfully created a library project called ng-simple-alert and a corresponding showcase called ng-simple-alert-showcase .

A simple alert library 🚨

Excellent. We now have our project setup; let’s implement the library. The goal of our library is to provide a service and a component which can be used to display some simple alerts.

Let’s first implement the service.

Our service exposes the different alert methods and streams them into the alertMessage$ Subject .

Next, let’s create the component which actually displays the messages.

This component just displays a message once the alertMessage$ emits new messages. If we click on the close button the close subject streams false. The close$ is merged into the alertMessage$ . So every time the close$ emits false, the messages will disappear.

That’s it. Our library is ready. 💪

Your first consumer — implementing a showcase

So let’s change in our simple-alert-showcase project and implement a showcase where we use our library.