ladder on brown wooden bookshelf

How to add Angular Material to a Angular Library

 

A while ago we made the call to migrate our angular apps under a mono-repo, and ran into a challenge. We wanted a shared UI-Library of sorts and wanted to leverage angular material on it as well as our own custom theme.

However we ran into a hairy bit and noticed that even though we added the module, the compiler was still angry with us, it couldn’t figure out where this module was for some reason.

After bit of playing around we managed to land on the solution and below is that exact approach we hope will help you too.

New Angular Workspace

  1. Create new workspace by running command ng new MonoRepoWorkspace --create-application false
  2. Go into the newly created workspace by typing cd MonoRepoWorkspace
  3. Use ng new to create your workspace WITHOUT a project and in the same directory ng new demo-workspace --directory=./ --create-application=false
    • This will create an angular workspace. It will look similar to a project, but it won’t do anything but fail if you type ng serve
  4. In the same folder (the ROOT of your workspace repo) generate your library, including a desired prefix) with ng generate demo-library or ng g demo-library --prefix=demo.
    • This will create a ‘projects’ folder inside of your workspace folder. It will place your new library inside your ‘projects’ folder.
  5. Then you’ll run ng build demo-library to run your initial build of your new library, which will create a dist folder in the root of your workspace.
  6. Next you will create your sandbox project that you will use while developing and testing your angular library with the ng generate command and your desired flags, something like this ng g application demo-sandbox --style=scss --routing=false
    • This will generate a normal angular project, following your flag instructions and place the newly generated project in your workspace’s projects folder demo-workspace/projects/demo-sandbox
  7. After your project has been generated, you can serve it up with the standard ng serve and it’ll appear on port 4200, no need to include the --project= flag for this, it will assume it correctly.
  8. Now you will finally add Angular Material schematic to your sandbox project with ng add command and using the --project= flag to identify which project Angular Material should run in (again, all of this is in your parent workspace directory) ng add @angular/material --project=demo-sandbox

 

keyboard_arrow_up