Angular material not working in an angular library

1k Views Asked by At

I have some angular projects and I have seen that there is a lot of code that can be reusable, so I thought on making some of the code part of a common library.

I created the library following the steps in the article: https://angular.io/guide/creating-libraries

I have tested it to a new angular app and it seems working ok, the problem comes when I tried to migrate some code that is using external libraries such as angular material.

In the workspace where I have the library I did:

ng add @angular/material

I created a new service like:

ng generate service Common

In this new service I added the following code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatSnackBar } from '@angular/material/snack-bar';

@Injectable({
  providedIn: 'root'
})

export class CommonService {
  waitDialog: any;
  
  
  constructor(private http: HttpClient, private _snackBar: MatSnackBar) {
    this.waitDialog = null;
  }

  ShowMessage(message: string) {
    this._snackBar.open(message, "Dismiss", {
      horizontalPosition: "right",
      verticalPosition: "top",
      duration: 5 * 1000
    });
  }
}

Then at my library module file I have:

import { NgModule } from '@angular/core';
import { VcmsLibraryComponent } from './components/vcms-library/vcms-library.component';
import { HttpClientModule } from '@angular/common/http';
import { MatSnackBarModule } from '@angular/material/snack-bar';

@NgModule({
  declarations: [
    VcmsLibraryComponent,
    ImportFileDialogComponent,
  ],
  imports: [
    HttpClientModule,
    MatSnackBarModule
  ],
  exports: [
    VcmsLibraryComponent
  ]
})
export class VcmsLibraryModule { }

After that I built the library with:

ng build

Installed the library from another app (in a different workspace) as:

npm install "file:./vcms-workspace//dist//vcms-library"

In my app I insterted the reference in app.module.ts (in the imports array) and make the necesary imports in the app.component, but when I try to start the app, I get the following error in the browser: enter image description here

1

There are 1 best solutions below

0
Brank Victoria On

I was able to fix this by adding in angular.json from the app that consumes the library:

"preserveSymlinks": true

Then I had the problem that everytime I made a chang ein the library it was not being reflected in the app so it provoked errors during compiling. I've seen that it is necesary to change the version of the library everytime I make a change as it takes the library from cache:

https://github.com/angular/angular-cli/issues/22380#issuecomment-994901588