Angular自定义库使用ngIf触发NG0303错误,求原因及解决方法
问题根源
NG0303错误的核心是NavigationComponent所在的模块未正确导入CommonModule。虽然你在DesignSystemModule中导入了CommonModule,但组件的模块归属逻辑混乱:NavigationComponent被错误地声明在DesignSystemModule中,而专属的NavigationModule却未声明该组件,导致库被引入应用后,组件依赖的*ngIf等指令无法被识别。
修复步骤
1. 调整NavigationComponent的模块归属
将NavigationComponent从DesignSystemModule的declarations和exports中移除,转移到NavigationModule中:
修改后的NavigationModule代码:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatIconModule } from '@angular/material/icon'; import { RouterModule } from '@angular/router'; import { NavigationComponent } from './navigation.component'; @NgModule({ declarations: [NavigationComponent], // 声明组件 imports: [ CommonModule, // 必须保留,提供NgIf等基础指令 MatIconModule, RouterModule // 若用到路由指令,可改为RouterModule.forChild([])配置路由 ], exports: [NavigationComponent] // 导出组件供外部模块使用 }) export class NavigationModule { }
2. 在DesignSystemModule中导入NavigationModule
修改DesignSystemModule,移除对NavigationComponent的直接声明,改为导入NavigationModule:
修改后的DesignSystemModule代码:
import { NgModule } from '@angular/core'; import { LibDesignSystemComponent } from './lib-design-system.component'; import { ButtonPrimaryComponent } from './button/button-primary/button-primary.component'; import { CommonModule } from '@angular/common'; import { NavigationModule } from './navigation/navigation.module'; // 导入NavigationModule @NgModule({ declarations: [ LibDesignSystemComponent, ButtonPrimaryComponent // 移除NavigationComponent的声明 ], imports: [ CommonModule, NavigationModule // 导入NavigationModule,使其组件可被外部访问 ], exports: [ LibDesignSystemComponent, ButtonPrimaryComponent, NavigationModule // 导出模块,规范对外暴露组件的方式 ] }) export class LibDesignSystemModule { }
3. 验证public-api.ts配置
确保public-api.ts中正确导出NavigationComponent或NavigationModule,示例:
export * from './lib/navigation/navigation.component'; export * from './lib/navigation/navigation.module'; export * from './lib/lib-design-system.module';
4. 重新构建并发布库
执行以下命令重新构建库,替换DevOps中的Artifact:
ng build your-library-name # 重新发布到DevOps Artifact仓库
本地/Storybook正常的原因
本地开发和Storybook环境中,可能通过全局导入CommonModule或组件加载路径的特殊性,掩盖了模块归属的问题;但库被打包发布后,Angular会严格按照模块声明解析依赖,未正确归属的组件会丢失指令依赖,从而触发NG0303错误。
内容的提问来源于stack exchange,提问作者SamBslm
相关产品推荐
相关产品推荐

