【问题标题】:Accessing angular library from angular app - StaticInjectorError in angular component with ElementRef in constructor从角度应用程序访问角度库 - 角度组件中的 StaticInjectorError 与构造函数中的 ElementRef
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多