Search code examples
angularelementref

Error while using "ElementRef" in one of the service in angular


ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[ElementRef]:
StaticInjectorError(Platform: core)[ElementRef]: NullInjectorError: No provider for ElementRef! Error: StaticInjectorError(AppModule)[ElementRef]:
StaticInjectorError(Platform: core)[ElementRef]: NullInjectorError: No provider for ElementRef!

This is the error I am getting in angular5 when I am making use of ElementRef in one of my services and I did import it like this:

import { Injectable,ElementRef } from '@angular/core';

Solution

  • You can't inject ElementRef to a service class,

    it is used only on component or directive,

    maintain service class to write business logic only,

    and try to use ElementRef in your component

    or create a directive and try to use that directive.

    For more details you can refer the below answer link,

    Injecting ElementRef to injecable error