Angular directives
Hi every one, this Article will show how to use the directive in Angular .
Angular have 2 kind of build-in directive
1. Attribute directive
2.Structural directive
first we will see the build-in Attribute directives
This is modify the behavior of HTML elements,attributes,properties,and components.
many NgModules such as the RouterModule and the FormModule defines their own attribute directives.
the most common attribute directives are
- NgClass :- it is use to add or removes the set of CSS classes
<h1 [ngClass]=”’myPass’”> Students List</h1>
here myPass is a css class we declared it


2.NgStyle :- it is use to set of many inline styles simultaneously and
and dynamically.
<h2 [ngStyle]=”{color:’green’}”> Finish </h2>

3. NgModel :- display a data property and update that property when the user makes changes.If we use the ngModel two-way data binding we must import the FormsModule in app.module.ts
import { FormsModule } from ‘@angular/forms’;


Next we will see the build-in Structural directives
It is responsible for HTML layout.
common built-in structural directives are
- NgIf :- it is conditionally create or destroy the subview of the template
2. NgFor :-it is repeater directive,a way to present list of item.
below i mention example of ngIf and ngFor …
students=[“Jhon”,”Devid”,”Vijay”,”Dhoni”];
age:number=20;

in here the condition is true then the students list will show.

In here the *ngFor use to list the students list.
3. NgSwitch :-It displays one element from among several possible elements, based on a switch condition.
It is actually a set of three, cooperating directives: NgSwitch,NgSwitchCase,NgSwitchDefault.


There are three kinds of directives in Angular
- component directive
- Attribute directive
- Structural directive
simple appHighlight attribute directive
first create the directive file :-use this command to create it. “ng g directive Highlight “.
in side this class we want to import the { Directive,ElementRef,HostListener } from ‘@angular/core’;
we want to initialize the ElementRef in the constructor.

ElementRef :- we can this to direct access to the DOM element using its nativeElement property.
@HostListener() function decorator allows you to handle events of the host element in the directive class
Then import the selector in out Html file (in this example the selector is “myHighlight”)

Thank all for reading this article 😊.I hope all are got some kind of knowledge related Angular directives.