Angular directives

kirushanthy jeyarajah
3 min readSep 10, 2020

--

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

  1. 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’;

when I type the name it will printed in the below section

Next we will see the build-in Structural directives

It is responsible for HTML layout.

common built-in structural directives are

  1. 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;

I initialized the age in component.ts file (age:number=20)

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

if I change the condition age>25 then the students list does’t 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.

when I click the student Jhon it will display ”he is good man

There are three kinds of directives in Angular

  1. component directive
  2. Attribute directive
  3. 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.

this is our directive class

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”)

this is the out put ,when the mouse is hover it the fontsize and font weight also changed.

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

--

--