我已经在 Angular 6 中创建了一个组件库,我想在我的组件库中全局使用 Angular 材料组件。
我试过导入 app.module.ts (不暴露给库) 我试过改变我的 main.ts 以包含 @NgModule 并导出一个“MainModule”,这个编译得很好,但似乎不是正确的方法去做这个?
我错过了什么吗?希望我有一些代码可以分享,但真的不知道从哪里开始。
任何帮助表示赞赏!
我已经在 Angular 6 中创建了一个组件库,我想在我的组件库中全局使用 Angular 材料组件。
我试过导入 app.module.ts (不暴露给库) 我试过改变我的 main.ts 以包含 @NgModule 并导出一个“MainModule”,这个编译得很好,但似乎不是正确的方法去做这个?
我错过了什么吗?希望我有一些代码可以分享,但真的不知道从哪里开始。
任何帮助表示赞赏!
如果你想在你的库组件中使用 Angular Material 组件,你应该像在普通的 Angular 应用程序中那样做。这意味着您应该将使用过的 Angular Material 模块导入库模块(和/或其子功能模块):
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatDialogModule, MatExpansionModule, MatIconModule } from '@angular/material';
import { LibraryComponent } from './library.component';
@NgModule({
imports: [
CommonModule,
MatDialogModule,
MatExpansionModule,
MatIconModule,
],
exports: [
LibraryComponent,
],
declarations: [
LibraryComponent
]
})
export class LibraryModule { }
您还可以创建一个自定义模块,该模块包含所有使用的 Angular Material 模块并将其导入其他模块(如本步骤的第二个代码块中所述:https ://material.angular.io/guide/getting-started#步骤 3-import-the-component-modules)。
正如评论中已经描述的那样:您不必 import BrowserAnimationsModule
,但使用您的库的项目必须导入它。
重要的是,您在库文件中@angular/material
定义。peerDependency
package.json
在你的 app.module.ts 中。
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
@NgModule({
imports: [
CommonModule,
MatInputModule,
MatButtonModule
],
})
export class AppModule {}
在 app.component.html 中
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="Favorite food" value="Sushi">
</mat-form-field>
<mat-form-field class="example-full-width">
<textarea matInput placeholder="Leave a comment"></textarea>
</mat-form-field>
</form>