0
votes

I'm using ElementRef in the CommentComponent which is exported to others modules like ArticleModule, ProductModule etc...

// 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 calls the CommentComponent from view like this:

<div class="article">
    .......
    <comments></comments>
</div>

Now when I'm trying to route through ArticleComponent, I'm getting:

core.js:1673 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[NgClass -> ElementRef]: StaticInjectorError(Platform: core)[NgClass -> ElementRef]: NullInjectorError: No provider for ElementRef! Error: StaticInjectorError(AppModule)[NgClass -> ElementRef]: StaticInjectorError(Platform: core)[NgClass -> ElementRef]: NullInjectorError: No provider for ElementRef!

It seems ElementRef cannot pass through 'provider' because when I remove it from CommentComponent everything works fine.

What is the problem ?

I'm using Angular 6 by the way

1
add --preserve-symlinks in your build commandNarendra
Move CommentComponent from providers array to declarationsyurzui
@yurzui CommentComponent belongs to CommentModule which mean it is already declared there ! You can see CommentModule inside ArticleModule imports.Amadou Beye

1 Answers

2
votes

Remove CommentComponent from providers list of AritcleModule. CommentComponent is already declared in CommentModule.

// Article Module

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

Remove ElementRef from constructor which is throwing this error and if you want to access the element then you can put the reference for element and use @ViewChild decorator in ts file.

Example :

html

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

ts

@ViewChild("ele") _eref: ElementRef;