Angular

Custom Directives In Angular

In this blog, we will learn custom directives in Angular.

The custom directive is a user-defined service that we can use in a project everywhere with use to applying its selector class. The custom directive is like a class object, we can use it many times.

To create a custom directive we have to replace @Component decorator with @Directive decorator.

For Example, Follow these steps to get to know how to create custom directives.

Step 1: Create a new Angular Project

Add a new directive by pasting this below code in the command prompt/ terminal

ng g directive customStyle

Step 2:  Add it to custom-style.directive.ts

In this file “appCustomStyle” selector is created, this selector can be used in any component.

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

@Directive({
  selector: '[appCustomStyle]'
})
export class CustomStyleDirective {
  constructor(private el : ElementRef, renderer : Renderer2) { 
    el.nativeElement.style.color ="blue";
    el.nativeElement.style.fontStyle ="italic";
    el.nativeElement.style.background = 'yellow';
    el.nativeElement.style.fontSize = "30px";  
  }
}

Step 3:  for apply styling, I have created two h2 tags. In one tag I will add an appCustomStyle selector.

appCustomStyle selector is added in the second h2 tag line. By these custom styles which we had added in custom-style.directive.ts will be applied directly in the second h2 tag.

<h2>Normal Head 2 text </h2>
<h2 appCustomStyle>Custom Directives text </h2>

Now, Run your project and see the output.

Ruju Desai

Web Developer at Vision Infotech

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago