'Add Angular Material to Nx Workspace

I'm wanting to add angular-material to my nx-workspace.

The angular material docs (https://material.angular.io/guide/getting-started) say I should run ng add @angular/material.

I've tried that in the root of my nx workspace, as well as in an application folder I want to add it to, as well as in a lib project folder I want to add it to. In all cases I get the message The add command requires to be run in an Angular project, but a project definition could not be found.

The Angular Material docs used to include instructions on how to add dependencies manually, but I can't find that anymore. Does anyone know how to add it to projects in an Nx workspace these days?



Solution 1:[1]

If you created the an empty workspace you don't have angular.json, you will have a workspace.json, which is almost identical I think.

Assuming that you have already generated an agular app:

  1. Install the angular material lib: yarn add @angular/material

  2. To see the avaible commands from the nx console: nx list @angular/material enter image description here

  3. To add angular material to the default project: nx generate @angular/material:ng-add enter image description here

PS. Probably it will thrown an error on nx not found/installed. yarn add -g @nrwl/cli. I think is possible to add angular material to another project, didn't try that yet

https://github.com/nrwl/nx/issues/3779#issuecomment-751136586

Solution 2:[2]

npm install @angular/material && npx nx g @angular/material:ng-add

Then follow the same as material docs

Solution 3:[3]

For what it's worth I created a new Angular project (without Nx) and ran the ng add @angular/material command there, then took a look at the diff that resulted, and applied those changes in the Nx workspace and that seems to work fine. Just wondering if there is a better way.

Solution 4:[4]

Yarn will cause build errors when using theming. I was running my build with yarn. It will complain about the @use '~@angular/material' as mat; being in a loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jithil
Solution 3 vicatcu
Solution 4 David Diomede