让Angular Material在Angular库中运行

4
我将尝试把 Angular Material 应用于一个 Angular Library。
我已经完成以下步骤:
1. 创建项目。
ng new test-project
  1. 添加 Angular Material
ng add @angular/material
  1. 创建库

ng g library test-lib

  1. 在test-lib package.json文件中将angular material添加为对等依赖
  "peerDependencies": {
    "@angular/common": "^7.2.0",
    "@angular/core": "^7.2.0",
    "@angular/material": "^7.3.7"
  }
在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 代码:

<test-lib></test-lib>

现在我运行应用程序时出现以下错误信息:

'mat-checkbox' 不是已知的元素: 1. 如果 'mat-checkbox' 是一个 Angular 组件,请确认它已经被加载到了该模块中。

显然,这是当引用缺失时标准的错误信息,但因为我已经添加了它们,所以我在想是否还需要在库内做其他事情以使其正常工作?

谢谢


你尝试从TestLibModule中导出MatCheckboxModule了吗?尝试使用exports: [TestLibComponent, MatCheckboxModule] - Benjamin O. P.
我刚刚尝试了一下,仍然收到错误信息。 - Sun
我认为你需要按照这个导出:export { MatCheckboxModule } from '@angular/material/checkbox' - Kushal Jayswal
你的意思是在public-api.ts文件中吗? - Sun
刚刚尝试了一下,出现了相同的错误。 - Sun
1个回答

4

本地编码后更新答案:

我按照您在问题中提到的所有步骤尝试了一遍,成功地运行了应用程序而没有出现任何错误。然而,我需要更新您的部分代码如下:

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. 测试库模块

无需更改

4. 使用<mat-checkbox>我的复选框</mat-checkbox>进行屏幕截图

enter image description here

5. 屏幕截图

enter image description here


我无法在StackBlitz中创建一个库。 - Sun
好的,让我按照您的步骤操作,然后再回复您。我相信这只是一个非常小的问题。 - Kushal Jayswal
如果这个答案解决了你的问题,请批准一下。谢谢 :) - Kushal Jayswal
请看第5步。在添加复选框后,它仍然有效吗? - Sun
请查看第5步(抱歉) - Sun
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接