【问题标题】:<selector> is not a known element Angular 9 custom library<selector> 不是已知元素 Angular 9 自定义库
【发布时间】:2020-07-04 05:20:32
【问题描述】:

我正在尝试创建一个包含服务和组件的自定义库。但是,当我这样做时,我得到了常见的“不是已知元素”错误。

即使我做了一个非常简单的示例,也会发生这种情况。重现步骤:

  1. ng new example --create-application=false
  2. cd example &amp;&amp; ng g library example-lib
  3. ng g application example-app
  4. ng build example-lib
  5. 将 example-lib 项目中的模块导入 example-app:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ExampleLibModule } from 'example-lib';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ExampleLibModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 将组件添加到example-app中的app.component.ts:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<lib-example-lib></lib-example-lib>`,
  // templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'example-app';
}

如果我按照上述步骤操作,我会收到描述的错误。这似乎只是组件的问题,因为如果我在 example-lib 中向服务添加虚拟方法:


import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ExampleLibService {

  constructor() { }

  hello() {
    return 'hello';
  }
}

然后将该服务导入到我的示例应用组件中:

import { Component } from '@angular/core';
import { ExampleLibService } from 'example-lib';

@Component({
  selector: 'app-root',
  // template: `<lib-example-lib></lib-example-lib>`,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'example-app';
  constructor(private exampleService: ExampleLibService) {
    this.title = this.exampleService.hello();
  }
}

这样做,一切正常,我可以正常访问我的服务。因此,这似乎只是组件的问题,但一切都具有来自角度 cli 的开箱即用配置。任何指导将不胜感激!

我的系统:

Angular CLI: 9.1.8
Node: 12.15.0
OS: darwin x64

【问题讨论】:

  • 您是否已将其添加到 ExampleLibModule 的 providers 数组中/您能否向我们展示示例库模块?
  • 你导出了示例库组件吗?

标签: angular typescript


【解决方案1】:

原来我的node_modules 中的某些东西导致了这个问题。我删除了它们(rm -rf node_modules)并重新安装了npm install,这(奇怪)似乎解决了它。

【讨论】:

    【解决方案2】:

    您正在导出 ExampleLibModule 并尝试将其用作组件。 检查 lib-component 并在中声明它

    declarations: [
        AppComponent
        // declare here the lib component 
      ] 
    

    【讨论】:

    • ExampleLibComponent 在我的 ExampleLibModule 的 declarationsexports 中,所以我应该可以导入它。我不需要像这样声明它 - 而且,这不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2019-06-27
    • 2020-05-23
    • 2021-09-02
    相关资源
    最近更新 更多