Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example

Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example

In this post we will give you information about Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example. Hear we will give you detail about Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div ExampleAnd how to use it also give you demo for it if it is necessary.

In this quick example, how to dynamically create a div, with an id and append it to the body element in an Angular 10 service. We’ll see how to use RendererFactory2 in services to create an instance of Renderer2.

In services, you can use RendererFactory2 to create a Renderer2 instance. For example:

import{Injectable,Renderer2,RendererFactory2}from'@angular/core';@Injectable({providedIn:'root'})exportclassDOMService{privaterenderer:Renderer2;constructor(rendererFactory:RendererFactory2){// Get an instance of Renderer2this.renderer=this.rendererFactory.createRenderer(null,null);}createDIV(){// Use Renderer2 to create the div elementconstdiv=this.renderer.createElement('div');// Set the id of the divthis.renderer.setProperty(div,'id','container');// Append the div to the body elementthis.renderer.appendChild(document.body,div);returndiv;}}

Creates and initializes a custom renderer that implements the Renderer2 base class. RendererFactory2

If you try to inject Renderer2 directly in a service you will get the following error because it can be only injected in components or directives:

UnhandledPromiserejection:StaticInjectorError[Renderer2]:StaticInjectorError[Renderer2]:NullInjectorError:NoproviderforRenderer2!;Zone:<root>;Task:Promise.then;Value:Error:StaticInjectorError[Renderer2]:StaticInjectorError[Renderer2]:NullInjectorError:NoproviderforRenderer2!

Hope this code and post will helped you for implement Angular 10 Renderer2 in Services with RendererFactory2: Append Dynamic Div Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US