Angular Directives


Angular Directives

Directives are instructions in the DOM. They specify how to place your components and business logic in the Angular.

Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular.

  1. Attribute directives
  2. Component Directives
  3. Structural Directives

Attribute directives

Attribute directives are used to change and modify the behavior of DOM  elements, attributes, properties, and components.

Attribute directives  seem as though an ordinary HTML Attribute and predominantly utilized in databinding and event binding.

  • NgClass  -  adds and removes a set of CSS classes.
  • NgStyle   - adds and removes a set of HTML styles.
  • NgModel - adds two-way data binding to an HTML form element.

// NgClass

<div [ngClass]="'first second'">...</div>

<div [ngClass]="['first', 'second']">...</div>

<div [ngClass]="{'first': true, 'second': false}">...</div>

<div [ngClass]="stringExp">...</div>

<div [ngClass]="{'class1 class2 class3' : true}">...</div>

<div [ngClass]="isSpecial ? 'special' : ''"></div>

// NgStyle

<div [ngStyle]="{'font-style': styleExp}">...</div>

<div [ngStyle]="setCurrentStyles">...</div>

<div [ngStyle]="{'max-width.px': widthExp}">...</div>

setCurrentStyles() {

  this.currentStyles = {

    'font-style':  this.italic     ? 'italic' : 'normal',

    'font-weight': !this.bold ? 'bold'   : 'normal',

    'font-size':   this.large    ? '24px'   : '12px'



// NgModel

<input [ngModel]="currentItem" (ngModelChange)="setUppercaseName($event)" id="example-uppercase">

Component Directives

Component directives are used in main class. They contain the detail of how the component should be processed, instantiated and used at runtime.


  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']


Structural Directives

Structural directives start with a * sign. These directives are used to manipulate and change the structure of the DOM elements. For example, *ngIf and *ngFor.

<div *ngFor="let obj of list; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">

  {{i}} {{obj .name}}


<ng-template ngFor let-obj  [ngForOf]="list" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">

  <div [class.odd]="odd">{{i}} {{obj .name}}</div>


<div *ngIf="hero" class="name">{{hero.name}}</div>