我在CommentComponent中使用 ElementRef
,它被导出到其他模块,如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 ERROR错误:未捕获(在承诺中):错误:StaticInjectorError(AppModule)[NgClass - > ElementRef]:StaticInjectorError(Platform:core)[NgClass - > ElementRef]:NullInjectorError:没有ElementRef的提供者!错误:StaticInjectorError(AppModule)[NgClass - > ElementRef]:StaticInjectorError(Platform:core)[NgClass - > ElementRef]:NullInjectorError:没有ElementRef的提供者!
似乎ElementRef无法通过'provider',因为当我从CommentComponent中删除它时,一切正常 .
问题是什么 ?
我顺便使用Angular 6
1 回答
从
AritcleModule
的提供者列表中删除CommentComponent
.CommentComponent
已在CommentModule
中声明 .从
constructor
中删除ElementRef
,这会抛出此错误,如果要访问该元素,则可以放置元素的引用并在ts文件中使用@ViewChild装饰器 .示例:
HTML
TS