Search code examples
angularangular-materialangular-workspace-configuration

Adding Angular material and consuming in workspace throws inject error


I started with Angular Workspace,

1. Project 1
2. Project 2
3. SharedLib //The sharedlibrary

in Project1 and Project2, I imported the sharedLib.

In SharedLib, I created a component with Material Button Component.

@NgModule({
  declarations: [
    HelloComponentComponent
  ],
  imports: [
     CommonModule,
     MatButtonModule
  ],
  exports: [
    HelloComponentComponent
  ]
})
export class SamplesharedlibraryModule { }

HelloComponent.html

 

<button mat-button color="primary">Primary</button>

Now getting this error

Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with EnvironmentInjector#runInContext. Find more at https://angular.io/errors/NG0203


Solution

  • You might be missing the setting in tsconfig. The dependencies of shared libraries should be added as a path in the tsconfig of the consuming application. In your case either Project1 or Project2.

    like this,

    {
      "paths": {
        "@angular/*": [
          "../.././node_modules/@angular/*"
        ]
      }
    }
    

    also you should have separate tsconfig file for shared libraries.