Introductions
In this article, we are going to see Angular directives. Directives in Angular are a Typescript class which is declared with decorator @Directive. These are DOM instruction sets, which decide how logic implementation can be done.
The angular directives are classified into three types
- Attribute directives
- Structural directives
- Components directives
Attribute directives
The first one, the attribute directives, are used to change the styles and behavior of the DOM element. We use attribute directives to apply a conditional style to elements, show or hide elements or dynamically change the behavior of a component according to a changing property. It provides the ability to create our custom attribute directive. Please follow the below codes to create our custom attribute directive.
Here I have mentioned existing directives in Angular are fairly easy. The ngClass directive is a good example of an existing Angular attribute directive.
- <style>
- .red{color: red}
- .green{color: green}
- </style>
- <p[ngClass]="{'red'=true, 'green'=false}">
- Angular attribute directive
- </p>
Next, we are going to create a custom attribute directive, Here I have the app.mydirective.ts file. Please copy the below codes.
- import {Directive, ElementRef} from'@angular/core';
- @Directive({
- selector:'[my-directive]'
- })
- exportclassMyDirective{
- constructor(elr:ElementRef){
- elr.nativeElement.style.background='yellow';
- }
- }
After creating the directive from @angular/core we can then use it. First, we need a selector like my-directive.
Then we created a class, MyDirective, to access any element of our DOM, we need to use ElementRef. Since it also belongs to the @angular/core package.it simple to import and use in our application.
use this newly created directive to the app.module.ts file.
- import { NgModule } from'@angular/core';
- import { BrowserModule } from'@angular/platform-browser';
- import { MyDirective } from'./app.mydirective';
- import { AppComponent } from'./app.component';
- @NgModule({
- imports: [ BrowserModule ],
- declarations: [ AppComponent, MyDirective ],
- bootstrap: [ AppComponent ]
- })
- exportclassAppModule { }



Join the conversation! Your thoughts help the community grow.