Developer Snippet Diary

Renderer2 in Angular | Add custom backgrounds, classes, attributes etc | Directives | Angular 15+

  • The native element property contains the reference to the underlying DOM object which gives us direct access to the DOM, bypassing the angular. This is not advisable for following reasons:
  • Angular keeps the Component & the view in Sync using Templates, data binding & change detection, etc All of them are bypassed when we update the DOM Directly.
  • DOM Manipulation works only in Browser. You will not able to use the App in other platforms like in a web Worker, in Server or in a Desktop, or in the mobile app, etc. where there is no browser.
  • The DOM APls do not sanitize the data. Hence it is posible to inject a script, thereby, opening our app an easy target for the XSS injection attack.

Move to app/custom_directives/ and open terminal and run command

ng generate directive greenbackground

it will create directive + add it in app.module.ts

app/custom_directives/greenbackground.directive.ts

import { Directive, ElementRef, OnInit, Renderer2 } from '@angular/core';
@Directive({
  selector: '[appGreenbackground]'
})
export class GreenbackgroundDirective implements OnInit {
  constructor(private element: ElementRef,private render: Renderer2){ }
  ngOnInit() {

    //this.render.setStyle(this.element.nativeElement,'backgroundColor','green'); //set inline style
    this.render.addClass(this.element.nativeElement,'backgroundblue'); //add class to element ,
    this.render.setAttribute(this.element.nativeElement,'title','This is better than old code'); //add class to element ,
} }

in view:

<div appGreenbackground>
  Its cool
</div>

app.module.ts

import { GreenbackgroundDirective } from './custom_directives/greenbackground.directive'

@NgModule({
  declarations: [
    GreenbackgroundDirective
  ],
Posted by: R GONDAL
Email: rizikmw@gmail.com