Build the local lib 🔨🤓
To create an angular components lib, we add an parameter to the usual "ng new":
ng new npm-test --create-application=false
cd npm-test
ng generate library custom-ui --prefix ui
ng generate component components/button --project=custom-ui
This will get you a simple component called button in projects/custom-ui/src/lib
Optional: Build a tester app 📖*️
We create a test app to see what we built in our library. For so, run the following:
ng generate application library-tester
There, to invoke the library in the library-tester app, do:
1) Export the component in *public-api.ts * by copying the line below:
export * from './lib/components/button.component/button.component';
2) Import the component in the library-tester app:
// app.ts
import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {ButtonComponent} from 'custom-ui';
@Component({
selector: 'app-root',
imports: [RouterOutlet, ButtonComponent],
templateUrl: './app.html',
styleUrl: './app.css',
})
export class App {
protected readonly title = signal('library-tester');
}
// app.html
<ui-button></ui-button>
Run these to verify in two different terminals:
ng serve --project=library-tester
ng build custom-ui --watch
Once done, in your localhost you should get something close to this:
Let's make the component configurable 🌶️🔥
Do the following changes:
1) In button.component.html:
<button class="custom-btn" [style.background-color]="color">
{{ text }}
</button>
2) Your button.component.ts should resemble this:
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'ui-button',
standalone: true,
imports: [CommonModule],
templateUrl: './button.component.html',
styleUrls: ['./button.component.css']
})
export class ButtonComponent {
@Input() text: string = 'Click me';
@Input() color: string = '#f68f3b';
}
2.a) Optional, add some custom css:
.custom-btn {
background-color: #3b82f6;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
.custom-btn:hover {
background-color: #2563eb;
}
3) In the library tester's app.html you can now pass those variables in the DOM definition:
<ui-button text="Hey there!" color="blue"></ui-button>
By doing all these steps, now your component should look like below:
Achievements 🎉🙌
- Created your first Angular library for reusability in your multiple projects
- Keep style, look-and-feel consistency across your apps
- Revisit the repo to verify if you missed something: https://github.com/elparaquecosadeque/npm-test
What's next 🏁🤓
- In this next article, we will learn to publish our Angular components library to npmjs (NPM) to make it available thru
npm installcommand
Happy coding! 👨💻


Top comments (0)