Sat. Apr 20th, 2024

Using Angular Material in the Lib

I needed to create a library mymiller-angular for a project I’ve been working on, that would provide components built around Angular Material that could be reused. After much searching, I came to the conclusion that the documentation for doing this is abysmal. Hopefully, I am able to clarify some of the steps to make this easier in the future.

  1. Don’t add your material libraries to your <dependencies> section in your package.json. Instead add them to the <devDependencies> section.
  2. Provide instructions for your library on what modules from Angular Material needs to be imported into the main project with your library.

I learned the hard way with pages not loading, when I included the Angular Material libraries as part of my library. The two small steps above and I had it working. However I had to piece this together from a number of different websites.

Singleton Service

So you need to add a singleton service to your library. Again this is where I found documentation and advice was wrong. Create your service and export it in your public-api.ts file.

Make sure your service has this:

@Injectable({
  providedIn: 'root'
})

DO NOT ADD it to the providers[] array in your module.ts file. Leave it out entirely of your module.ts file. Then add it to the provider’s array in your main application’s module.ts file. This will allow only a single instance of your service to exist.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.