custom directive in angular
How To Create Custom Directive In Angular

In This Blog, you are going to learn that how to create custom directives in angular application. Some times pre-defined directives does not fulfill our requirements then we have to create custom directives in our angular application, in that way we can achieve our tasks in our angular application.

Directives In Angular

  • In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior.
  • The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements.

What Is Meant By Directives in Angular?

  • In Angular, Directives are meant to be a function that executes when found in the DOM by the Angular compiler to extend the power of the HTML with new syntax.
  • In Angular, Directives have a name and can be predefined or custom-defined so that they can be called anything.

Types of Directives in Angular

There are three types of directives in angular, namely, Component, Structure Directives and attribute directives, In this blog we are going to create custom attribute directive.

Creating Our Own Attribute Directive In Angular

  • Custom Directive is very similar to creating the Angular component.
  • The custom directive is created using the @Directive decorator to replace the @component decorator.

Command For Creating Custom Attribute Directive

ng g directive shared/ChangeMe

Source Code

change-me.directive.ts File Code

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

@Directive({
  selector: '[appChangeMe]'
})
export class ChangeMeDirective {

  @Input() myColor = '';
  @Input() myBgColor = '';

  constructor(private el:ElementRef) {
    // this.el.nativeElement.style.color = "red";
    // this.el.nativeElement.style.backgroundColor = "yellow";
    // this.el.nativeElement.innerHTML = 'Hello Adil';
  }

  ngOnInit(){
    this.el.nativeElement.style.color = this.myColor;
    this.el.nativeElement.style.backgroundColor = this.myBgColor;
  }

}

app.component.html File Code

<p>Welcome To Angular By Learning Never Ends</p>

<h1 appChangeMe myColor="blue" myBgColor="orange">Hello My Lovely Viewers</h1>

<h1 appChangeMe myColor="green" myBgColor="pink">Hello My Lovely Viewers</h1>

Download Notes Of This Blog From the link given below

https://www.mediafire.com/file/2py9783jjqn14w5/46+-+CUSTOM+DIRECTIVES.pptx/file

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *