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

时间:2020-06-11 00:09:04

标签: angular typescript

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

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

  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. 将模块从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';
  }
}

,然后将该服务导入到我的example-app组件中:

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

2 个答案:

答案 0 :(得分:1)

原来是我的node_modules中的某件事引起了问题。我删除了它们(rm -rf node_modules),然后重新安装了npm install,这似乎很奇怪。

答案 1 :(得分:0)

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

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