Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Angular Material to work in angular library

I'm trying to get Angular Material to work within an Angular Library.

These are the steps I have taken:

  1. Create project
ng new test-project
  1. Add Angular Material
ng add @angular/material
  1. Create Library

ng g library test-lib

  1. Add reference to angular material to peer dependencies within test-lib package.json file
  "peerDependencies": {
    "@angular/common": "^7.2.0",
    "@angular/core": "^7.2.0",
    "@angular/material": "^7.3.7"
  }
  1. Within test-lib-component add the html for a Angular Material CheckBox
@Component({
  selector: 'test-lib',
  template: `
    <p>
      test!
    </p>
    <mat-checkbox>my checkbox</mat-checkbox>
  `,
  styles: []
})
  1. Build library

ng build test-lib --watch

  1. Within application app.module add references for component from test-lib
import { TestLibComponent } from 'test-lib'
@NgModule({
  declarations: [
    AppComponent,
    TestLibComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. Within the library project, within the test-lib.module I add the references to the Angular Material CheckBox Module
import { NgModule } from '@angular/core';
import { ControlLibraryComponent } from './control-library.component';
import { MatCheckboxModule } from '@angular/material/checkbox';

@NgModule({
  declarations: [TestLibComponent],
  imports: [
    MatCheckboxModule
  ],
  exports: [TestLibComponent]
})
export class TestLibModule { }
  1. Finally within the main apps app.component.html file I add the html for the library using the correct selector

<test-lib></test-lib>

I now run the app and I receive the following error:

'mat-checkbox' is not a known element: 1. If 'mat-checkbox' is an Angular component, then verify that it is part of this module.

This is obviously the standard message when a reference is missing but as I've added them I'm wondering what else I need to do within a library to get this to work?

Thanks

like image 407
Sun Avatar asked Sep 16 '25 07:09

Sun


1 Answers

Updating answer after local coding:

I tried all the steps mentioned in the question by you and I could run the application without any error. However, I need to update some of your code as below:

1. app.module

import { TestLibModule } from 'test-lib';    // <-- this

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    TestLibModule    // <-- this
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. Make sure of the selector name

<lib-test-lib></lib-test-lib>

3. test-lib.module

No change required

4. Screenshot with <mat-checkbox>my checkbox</mat-checkbox>

enter image description here

5. Screenshot

enter image description here

like image 171
Kushal J. Avatar answered Sep 19 '25 14:09

Kushal J.