angular - 从角度应用程序访问角度库 - 角度组件中的 StaticInjectorError 与构造函数中的 ElementRef
问题描述
我按照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;
}
}
我尝试在创建的角度应用程序中使用这个组件。我得到以下错误。
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 中可用?
谢谢巴桑特
解决方案
您需要ElementRef
与@ViewChild
装饰器一起使用:示例:
@ViewChild('idOfTheDiv/ButtonAsInYourHTML',{ static: true }) private idOfTheDiv/Button:ElementRef;
你可以在这里阅读更多https://alligator.io/angular/viewchild-access-component/
推荐阅读
- excel - 需要帮助修复 Excel 中的 IF(AND 语句
- sql - 我得到了用户元键的值,例如 a:1:{s:8:"investor";b:1;}
- javascript - JavaScript - 从数组中取出对象并将其内容放在相同的高度
- javascript - React-Native AsyncStorage:TypeError:无法读取未定义的属性“setItem”
- php - Laravel array_merge():参数 #2 不是 ServiceProvider.php 中的数组
- http - 为什么 Elastic Cloud 提供专用端口 (9243) 而不是仅使用默认端口 (443)?
- python - 如何使用 python 在 Maya 2018 中将着色器覆盖添加到渲染层
- javascript - Vue js / Nodejs Java Script 导出 docx 文件
- python - 使用 Postman 进行 Django Rest Framework 令牌身份验证
- java - 向 layout-ldrtl (RTL) 添加布局会导致应用崩溃