<selector> 不是已知元素 Angular 9 自定义库



我正在尝试创建一个同时具有服务和组件的自定义库。但是,当我这样做时,我收到常见的" 不是已知元素"错误。

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

  1. ng new example --create-application=false
  2. cd example && ng g library example-lib
  3. ng g application example-app
  4. ng build example-lib
  5. 将模块从示例库项目导入示例应用程序:
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

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

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

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

最新更新