Developer Snippet Diary

Custom Attribute Directive like ngIf | Directives | Angular 15+

Directives are simply an instruction to the DOM.

Directives in Angular:

  1. Component is a directive with a template. ie AppComponent
  2. Attribute directive can be used as an attribute to change the behaviour or appearance of anelement, component or other directives. ie ngstyle & ngclass
  3. Structural directive controls the DOM element, using which we can add or remove elements from DOM. ie nglf & ngFor

We will create a custom directive that change Background Color to red

1.create a class inside app/custom_directives/setbackground.directive.ts

import {Directive,ElementRef,OnInit} from "@angular/core";
@Directive(
    {
        selector:'[setBG]'
    }
)
export class SetBackgroundDirective implements OnInit{
    private element: ElementRef;
    constructor(element: ElementRef){
       this.element = element;
    }
    ngOnInit() {
        this.element.nativeElement.style.backgroundColor="red";
    }
}

2. import and add it in app.module.ts

import {SetBackgroundDirective} from './custom_directives/setbackground.directive'

@NgModule({
  declarations: [
    SetBackgroundDirective
  ]

3. use it in any view as 

<div  setBG>
 I Have red background using custom directive.
</div>
Posted by: R GONDAL
Email: rizikmw@gmail.com