【发布时间】:2020-06-10 13:36:17
【问题描述】:
我通过关注https://angular.io/guide/creating-libraries 创建了 Angular 库(名为 ng-library)。
- 使用
ng build ng-library构建它 - 使用
yarn link使其可用于其他角度应用程序 - 创建了一个角度应用程序并使用
yarn link ng-library链接库
我可以使用模块内的组件和服务。一切都好!
现在我在使用 ElementRef 的 ng-library 中添加了一个新的角度组件。
import { Component, NgZone, Input, Output, forwardRef } from '@angular/core';
import { ChangeDetectionStrategy, ElementRef, EventEmitter } from '@angular/core';
@Component({
selector: 'new-component',
template: '<ng-content></ng-content>'
})
export class NewComponent {
protected el: HTMLElement;
constructor(r: ElementRef, protected z: NgZone) {
this.el = r.nativeElement;
}
}
我尝试在创建的 Angular 应用程序中使用此组件。我遇到了错误。
AppComponent.html:1 ERROR NullInjectorError: StaticInjectorError(AppModule)[NewComponent-> ElementRef]:
StaticInjectorError(Platform: core)[NewComponent -> ElementRef]:
NullInjectorError: No provider for ElementRef!
at NullInjector.get (http://localhost:4200/vendor.js:36417:27)
at resolveToken (http://localhost:4200/vendor.js:51335:24)
at tryResolveToken (http://localhost:4200/vendor.js:51261:16)
at StaticInjector.get (http://localhost:4200/vendor.js:51111:20)
at resolveToken (http://localhost:4200/vendor.js:51335:24)
at tryResolveToken (http://localhost:4200/vendor.js:51261:16)
at StaticInjector.get (http://localhost:4200/vendor.js:51111:20)
at resolveNgModuleDep (http://localhost:4200/vendor.js:62298:29)
at NgModuleRef_.get (http://localhost:4200/vendor.js:63364:16)
at resolveDep (http://localhost:4200/vendor.js:63895:45)
这就是我在 Angular 应用程序中添加模块的方式。
import { NgLibraryModule } from "ng-library";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, NgLibraryModule.forRoot()],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
错误提示 ElementRef 的提供程序不可用。如何使 ElementRef 在 Angular 库中的 NgModule 中可用?
谢谢 巴桑特
【问题讨论】:
标签: angular angular-library ng-modules