Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject Renderer2 into custom service in Angular 4

Tags:

angular

I'm trying to inject Renderer2 into my custom service and it's failing with the error as below:

ERROR Error: StaticInjectorError[Renderer2]: 
  StaticInjectorError[Renderer2]: 
    NullInjectorError: No provider for Renderer2!

It's a brand new angular app created using cli and my custom service I created is:

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

@Injectable()
export class FontsService {

  constructor(private renderer: Renderer2) { 
    console.log(this.renderer);
  }

  getFonts() {
    return 'Ubuntu';
  }

}

And app.module is very simply just providing the newly created service:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FontsService } from './fonts.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [FontsService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Any help please?

Thank you.

like image 491
Venkat Avatar asked Dec 04 '25 07:12

Venkat


1 Answers

There is the way which Angular using internally in webworkers, for example.

I've solved the problem with the code below:

import { Renderer2, RendererFactory2 } from '@angular/core';

@Injectable()
class Service {
    private renderer: Renderer2;

    constructor(rendererFactory: RendererFactory2) {
        this.renderer = rendererFactory.createRenderer(null, null);
    }
}

Parameters of RendererFactory2.createRenderer method are:

  • hostElement with type any
  • type with type RendererType2|null

You can see that (null, null) parameters are here: https://github.com/angular/angular/blob/e3140ae888ac4037a5f119efaec7b1eaf8726286/packages/core/src/render/api.ts#L129

like image 95
Eugene Gavrilov Avatar answered Dec 06 '25 23:12

Eugene Gavrilov