【问题标题】:Getting Angular Material to work in angular library让 Angular Material 在 Angular 库中工作
【发布时间】:2020-02-01 16:40:39
【问题描述】:

我正在尝试让 Angular 材质在 Angular 库中工作。

这些是我采取的步骤:

  1. 创建项目
ng new test-project
  1. 添加角度材质
ng add @angular/material
  1. 创建库

ng g library test-lib

  1. 在 test-lib package.json 文件中添加对 Angular 材质的引用到对等依赖项
  "peerDependencies": {
    "@angular/common": "^7.2.0",
    "@angular/core": "^7.2.0",
    "@angular/material": "^7.3.7"
  }
  1. 在 test-lib-component 中为 Angular Material CheckBox 添加 html
@Component({
  selector: 'test-lib',
  template: `
    <p>
      test!
    </p>
    <mat-checkbox>my checkbox</mat-checkbox>
  `,
  styles: []
})
  1. 构建库

ng build test-lib --watch

  1. 在应用程序 app.module 中为来自 test-lib 的组件添加引用
import { TestLibComponent } from 'test-lib'
@NgModule({
  declarations: [
    AppComponent,
    TestLibComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 在库项目的 test-lib.module 中,我添加了对 Angular Material CheckBox 模块的引用
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. 最后在主应用 app.component.html 文件中,我使用正确的选择器为库添加了 html

&lt;test-lib&gt;&lt;/test-lib&gt;

我现在运行应用程序并收到以下错误:

'mat-checkbox' 不是已知元素: 1.如果'mat-checkbox'是一个Angular组件,那么验证它是这个模块的一部分。

这显然是缺少引用时的标准消息,但是当我添加它们时,我想知道在库中我还需要做什么才能使其正常工作?

谢谢

【问题讨论】:

  • 您是否尝试从TestLibModule 导出MatCheckboxModule?试试exports: [TestLibComponent, MatCheckboxModule]
  • 我刚刚尝试过,但仍然收到错误消息。
  • 我认为您需要按此导出:export { MatCheckboxModule } from '@angular/material/checkbox';
  • 你的意思是在 public-api.ts 文件中吗?
  • 刚试过,同样的错误

标签: angular angular-material angular-library


【解决方案1】:

本地编码后更新答案:

我尝试了您在问题中提到的所有步骤,并且可以运行该应用程序而不会出现任何错误。但是,我需要更新您的一些代码,如下所示:

1。 app.module

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

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

2。确保选择器名称

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

3。 test-lib.module

无需更改

4。截图&lt;mat-checkbox&gt;my checkbox&lt;/mat-checkbox&gt;

5。截图

【讨论】:

  • 你能分享stackblitz.comsn-p以便更好地理解吗?
  • 我无法在 stackblitz 中创建库
  • 好的,让我按照您的步骤操作,然后再回复您。我确信这是非常小的缺失。
  • 谢谢。真的很感激这一点。我也相信这会很简单。
  • 我已经更新了一些答案。请尝试。
猜你喜欢
  • 1970-01-01
  • 2020-12-01
  • 2022-12-20
  • 2018-07-22
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 2020-04-04
  • 2021-04-14
相关资源
最近更新 更多