【问题标题】:component selector is not a known element组件选择器不是已知元素
【发布时间】:2019-09-27 06:40:15
【问题描述】:

我有 2 个模块 AppModuleMyArtModule,其中声明了一些组件。

当我尝试在GraphicsComponent 中使用ConfirmComponent 选择器时,它工作正常,但是当我尝试在MyArtComponent 中使用ConfirmComponent 选择器时,它抛出错误'artifi-confirm-alert' is not a known element:

'artifi-confirm-alert' 不是已知元素:

  1. 如果 'artifi-confirm-alert' 是一个 Angular 组件,则验证它是该模块的一部分。

  2. 如果“artifi-confirm-alert”是 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”中 禁止显示此消息。

  • 应用模块
    • 图形组件
    • 确认组件
    • MyArt 模块
      • 我的艺术组件

AppModule 代码

@NgModule({
  declarations: [
    GraphicsComponent,
    ConfirmAlertComponent
  ],
  imports: [
    BrowserModule,
    MyArtModule
  ],
  ...
})

MyArtModule 代码

@NgModule({
  declarations: [
    MyArtComponent,
  ],
  imports: [
    CommonModule
  ],
  providers: [
    MyArtService
  ],
  exports: [
    MyArtComponent
  ]
})

复制的问题代码 - https://stackblitz.com/edit/skdroid-childmodule-in-child-component

我已经创建了 OneModuleOneComponentTwoModuleTwoComponent

<app-one></app-one><app-two></app-two> 可以在 AppComponent 中访问。

但无法访问 AppOne 组件中的<app-two></app-two>

【问题讨论】:

    标签: angular angular7


    【解决方案1】:

    您的 ConfirmComponent 和 GraphicsComponent 在同一个模块中!于是他们就认识了! 但是您正在尝试将该 ConfirmComponent 用于另一个模块中的另一个组件(在您的情况下: MyArtModule ),它不知道该组件是否存在!

    您必须导出 ConfirmComponent 以使其对整个应用程序启用!

    在AppModule的exports数组中添加ConfirmComponent

    exports: [
      ConfirmComponent
    ]
    

    【讨论】:

    • 在 AppModule 的导出数组中添加了 ConfirmComponent 但仍然出现同样的错误
    • 你能把confirm-component.ts文件里面的内容发过来吗?
    • 没什么,只是一个新组件。请检查问题我添加了复制问题的链接。
    【解决方案2】:

    您正试图在子模块组件中访问父模块组件。创建一个共享模块并在其中添加组件。

    @NgModule({
      declarations: [ConfirmComponent],
      exports: [ConfirmComponent],
    })
    
    export class SharedModule {
    }
    

    并将其添加到 AppModule 中:

    @NgModule({
      declarations: [
        GraphicsComponent,
      ],
      imports: [
        BrowserModule,
        MyArtModule,
        SharedModule
      ],
      ...
    })
    

    并将其导入您的 ArtModule:

    @NgModule({
      imports: [
        CommonModule,
        SharedModule
      ],
      declarations: [ConfirmAlertComponent],
      exports: [
        ConfirmAlertComponent
      ]
    })
    export class MyArtModule { }
    

    Stackblitz

    【讨论】:

    • 我为确认组件创建了一个新模块并在应用程序模块中导入但仍然出现相同的错误,尝试在 stackbliz 中复制链接有问题。
    猜你喜欢
    • 2020-10-24
    • 2018-09-18
    • 2013-02-24
    • 2017-11-09
    • 2019-03-30
    • 2021-09-16
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多