【问题标题】:Error while using “ElementRef” in exported component在导出的组件中使用“ElementRef”时出错
【发布时间】: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
  • CommentComponentproviders数组移动到declarations
  • @yurzui CommentComponent 属于 CommentModule 这意味着它已经在那里声明了!您可以在 ArticleModule 导入中看到 CommentModule。

标签: javascript angular


【解决方案1】:

AritcleModule 的提供者列表中删除CommentComponentCommentComponent 已在 CommentModule 中声明。

// Article Module

@NgModule({
    declarations: [ ArticleComponent], 
    providers: [ArticleService, CommentService, CommentComponent ], //<-- remove from here
    schemas: [ NO_ERRORS_SCHEMA ]
})

从引发此错误的constructor 中删除ElementRef,如果您想访问该元素,则可以将元素的引用放在ts 文件中并使用@ViewChild 装饰器。

示例:

html

<div #ele>hello/div> <!-- element reference goes here -->

ts

@ViewChild("ele") _eref: ElementRef;

【讨论】:

  • CommentComponent 属于 CommentModule 这意味着它已经在那里声明了!您可以在 ArticleModule 导入中看到 CommentModule。
  • 然后您可以简单地将其从ArticleModule 中删除,并且不要忘记从CommentModule 导出CommentComponent
  • CommentComponent 已经被 CommentModule 导出了!检查更新
  • 那么一切就绪。它应该可以工作,如果没有,那么分享你现在得到的错误。
  • 与帖子中描述的错误相同!问题在于ElementRef,因为当我从 CommentComponent 中删除它时,一切正常。
猜你喜欢
  • 2018-12-12
  • 2019-11-06
  • 2018-03-28
  • 2019-06-26
  • 2018-09-17
  • 2021-05-07
  • 1970-01-01
  • 2014-02-03
  • 2017-02-11
相关资源
最近更新 更多