You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular自定义库编译报NG8001:'ngb-accordion'不是已知元素如何解决

问题根源
  • 对@angular/elements的使用完全错误:ngb-accordion是ng-bootstrap官方封装的标准Angular组件,并非Web Component,你将自定义的CustomAccordionComponent注册为ngb-accordion自定义标签,反而覆盖了ng-bootstrap原有组件的标签指向,导致依赖混乱。
  • 库模块的导出配置缺失:CustomAccordionModule只声明了自定义组件,没有将其导出,外部模块无法正常引用该组件。
  • 引入了不必要的依赖与配置:库模块中不应该导入BrowserModule(该模块只能在应用根模块导入一次),同时CUSTOM_ELEMENTS_SCHEMA属于不必要配置,反而会掩盖组件未正常导入的真实错误。
  • 库依赖管理不独立:Angular 库需要独立维护自身的依赖导入,你之前直接在应用中写代码能正常运行,是因为应用模块已经全局导入了NgbModule或NgbAccordionModule,但挪到库内后库自身的模块没有独立导入对应依赖就会识别不了标签。
解决步骤
  1. 移除所有@angular/elements相关代码
    删除CustomAccordionModule中的ngDoBootstrap方法、createCustomElement调用、customElements注册逻辑,这部分代码完全不需要,反而会造成冲突。

  2. 修正CustomAccordionModule配置
    修改后的模块代码如下:

import { NgModule } from '@angular/core';
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
import { CustomAccordionComponent } from './custom-accordion.component';
import { CommonModule } from '@angular/common';

@NgModule({
    imports: [CommonModule, NgbAccordionModule],
    declarations: [CustomAccordionComponent],
    // 新增exports配置,导出封装的组件供外部使用
    exports: [CustomAccordionComponent]
})
export class CustomAccordionModule { }
  1. 移除不必要的schema配置
    删除HomeModule以及库所有模块中的schemas: [CUSTOM_ELEMENTS_SCHEMA]配置,该配置仅用于引入原生Web Component的场景,你当前的需求不需要用到。

  2. 检查库根模块的导出
    如果你的库对外暴露的统一入口是CustomModule,需要在CustomModule中导入并重新导出CustomAccordionModule,示例如下:

@NgModule({
  imports: [CustomAccordionModule, 其他库组件模块],
  exports: [CustomAccordionModule, 其他库组件模块]
})
export class CustomModule {}

完成以上配置后重新构建库即可正常使用。

内容的提问来源于stack exchange,提问作者Prateek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 01:36:03