我试图在其他模块中使用我在AppModule中创建的组件。我得到以下错误:

Uncaught (in promise):错误:模板解析错误 'contacts-box'不是已知元素: 如果'contacts-box'是一个Angular组件,那么验证它是否是这个模块的一部分。 如果'contacts-box'是一个Web组件,那么在'@NgModule '中添加'CUSTOM_ELEMENTS_SCHEMA'。模式来抑制此消息。

我的项目结构很简单:

我将页面保存在pages目录中,其中每个页面保存在不同的模块中(例如customers-module),每个模块都有多个组件(例如customers-list-component, customers-add-component等)。我想在这些组件中使用我的ContactBoxComponent(例如在customers-add-component内部)。

As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

我错过了什么?


当前回答

对于我的应用程序模式,一旦我在app.module.ts文件中声明了我的LandingPageComponent,就可以将子模块导入其中。

我刚开始一个新项目,并认为其中一些模式是理所当然的。

其他回答

我花了半天时间来解决这个问题。问题出在进口方面。我的HomeModule有html中包含的homeComponent。ProductComponent是ProductModule的一部分。我在导入中添加了ProductModule到HomeModule,但忘记在导入中添加HomeModule到AppModule。添加后,问题消失了

这个问题可能看起来古老而奇怪,但是当我试图加载一个模块(惰性加载)并得到相同的错误时,我意识到我错过了作为一个大模块的一部分发布的组件的exports子句。

这个角。Link解释了原因:模块内的组件/服务,默认情况下保持私有(或受保护)。要使它们公开,您必须导出它们。

扩展@Robin Djikof的回答,用@live-love代码示例,这是我的案例中技术上缺失的部分(Angular 8):

@NgModule({
  declarations: [
    SomeOtherComponent,
    ProductListComponent
  ],
  imports: [
    DependantModule
  ],
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
})
export class SomeLargeModule { }

我在Angular CLI: 10.1.5中也遇到了同样的问题 代码运行正常,但错误显示在VScode v1.50中

通过杀死终端(ng serve)并重新启动VScode来解决。

我也遇到过类似的问题。事实证明,ng generate component(使用CLI 7.1.4版)为AppModule添加了子组件的声明,但没有添加到模拟它的TestBed模块。

“英雄之旅”示例应用程序包含一个HeroesComponent,它带有选择器app- Heroes。应用程序运行正常时,但ng test产生这个错误消息:'app-heroes'不是一个已知元素。手动将HeroesComponent添加到configureTestingModule(在app.component.spec.ts中)的声明中可以消除这个错误。

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeroesComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
}

在我的例子中,问题是模块中缺少组件声明,但即使添加了声明,错误仍然存在。我不得不停止服务器并在VS Code中重新构建整个项目以消除错误。