【发布时间】:2018-11-17 02:31:16
【问题描述】:
我在 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(平台:核心)[NgClass -> ElementRef]: NullInjectorError:没有提供 ElementRef! 错误:StaticInjectorError(AppModule)[NgClass -> ElementRef]: StaticInjectorError(平台:核心)[NgClass -> ElementRef]: NullInjectorError: ElementRef 没有提供者!
似乎 ElementRef 无法通过“提供者”,因为当我从 CommentComponent 中删除它时,一切正常。
有什么问题?
顺便说一下,我正在使用 Angular 6
【问题讨论】:
-
在你的构建命令中添加 --preserve-symlinks
-
将
CommentComponent从providers数组移动到declarations -
@yurzui CommentComponent 属于 CommentModule 这意味着它已经在那里声明了!您可以在 ArticleModule 导入中看到 CommentModule。
标签: javascript angular