首页 > 解决方案 > 从角度应用程序访问角度库 - 角度组件中的 StaticInjectorError 与构造函数中的 ElementRef

问题描述

我按照https://angular.io/guide/creating-libraries创建了 Angular 库(名为 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;
  }
}

我尝试在创建的角度应用程序中使用这个组件。我得到以下错误。

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 中可用?

谢谢巴桑特

标签: angularangular-libraryng-modules

解决方案


您需要ElementRef@ViewChild装饰器一起使用:示例: @ViewChild('idOfTheDiv/ButtonAsInYourHTML',{ static: true }) private idOfTheDiv/Button:ElementRef;

你可以在这里阅读更多https://alligator.io/angular/viewchild-access-component/


推荐阅读