我ElementRef
在 CommentComponent 中使用,它被导出到其他模块,如 ArticleModule、ProductModule 等......
// CommentModule
@NgModule({
exports: [ CommentComponent ],
declarations: [ CommentComponent ],
providers: [ CommentService]
})
export class CommentModule { }
// Comment Component (belongs to CommentModule)
@Component({
selector: 'comments',
templateUrl: 'comment.component.html',
styleUrls: ['comment.component.scss']
})
export class CommentComponent implements OnInit {
suggOnTyping: string = 'hidden';
constructor(private _eref: ElementRef){}
@HostListener('document:click', ['$event'])
onClickOutside(event: any) {
event.preventDefault();
event.stopPropagation();
if (!this._eref.nativeElement.contains(event.target))
this.suggOnTyping = 'hidden';
}
}
// Article Module
@NgModule({
imports: [
CommonModule,
RouterModule,
CommentModule,
ArticleRoutingModule],
declarations: [ ArticleComponent ],
providers: [ArticleService, CommentService, CommentComponent],
schemas: [ NO_ERRORS_SCHEMA ]
})
ArticleComponent 像这样从视图中调用 CommentComponent:
<div class="article">
.......
<comments></comments>
</div>
现在,当我尝试通过 ArticleComponent 路由时,我得到:
core.js:1673 错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule)[NgClass -> ElementRef]:StaticInjectorError(Platform:core)[NgClass -> ElementRef]:NullInjectorError:没有提供 ElementRef!错误:StaticInjectorError(AppModule)[NgClass -> ElementRef]: StaticInjectorError(Platform: core)[NgClass -> ElementRef]: NullInjectorError: No provider for ElementRef!
似乎 ElementRef 无法通过“提供者”,因为当我从 CommentComponent 中删除它时,一切正常。
问题是什么 ?
顺便说一下,我正在使用 Angular 6
CommentComponent
从 的提供者列表中删除AritcleModule
。CommentComponent
已经在CommentModule
.
// Article Module
@NgModule({
declarations: [ ArticleComponent],
providers: [ArticleService, CommentService, CommentComponent ], //<-- remove from here
schemas: [ NO_ERRORS_SCHEMA ]
})
ElementRef
从中删除constructor
抛出此错误,如果您想访问该元素,则可以将元素的引用放在 ts 文件中并使用 @ViewChild 装饰器。
html
<div #ele>hello/div> <!-- element reference goes here -->
ts
@ViewChild("ele") _eref: ElementRef;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句