在导出的组件中使用“ ElementRef”时出错

时间:2018-11-17 02:31:16

标签: javascript angular

我在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错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule)[NgClass-> ElementRef]:     StaticInjectorError(平台:核心)[NgClass-> ElementRef]:       NullInjectorError:没有提供ElementRef的提供者!   错误:StaticInjectorError(AppModule)[NgClass-> ElementRef]:     StaticInjectorError(平台:核心)[NgClass-> ElementRef]:       NullInjectorError:没有ElementRef的提供程序!

似乎ElementRef无法通过'provider',因为当我从CommentComponent删除它时,一切正常。

出什么问题了?

我正在使用Angular 6

1 个答案:

答案 0 :(得分:2)

CommentComponent的提供者列表中删除AritcleModuleCommentComponent已在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;