Angular Directives are used to create or change structure and behavior of DOM Elements. Directive are mainly used to manage forms, lists, tables and styles in Angular.

There are three types of directives in angular.

Types of Directives

  1. Structural
  2. Attribute
  3. Component

Structural directives such as *ngFor and *ngIf are used to iterate or to execute code only if condition is met.

Attribute directives like NgStyle and NgModel are used to add inline css and declare Model (data logic) of application.

Component directives are most commonly used directives and have their own template unlike Structural and Attribute directives.


Structural Directive

Structural directives are used to change structural of DOM Elements. There are three structural directives in Angular.

Types of Structural Directive

  1. NgIf
  2. NgFor
  3. NgSwitch

NgIf directive

ngIf directive is used to show an element if condition is true. Like display a paragraph only if condition is true, else hide it.

ngIf in Angular

NgFor directive

ngFor directive is used to create an element through loop. It is used for Array, Objects and JSON Data.

ngFor in Angular

NgSwitch

ngSwitch directive is used to show or hide element based of switch condition.

ngSwitch in Angular

Attribute Directive

Attribute directive ar used to change the behavior of elements or components. ngStyle is used to add inline css in elements and ngModel to use add Two Way Data Binding in Angular.

Type of attribute directives

  1. ngClass
  2. ngStyle
  3. ngModel

NgClass

NgClass directive is used to add or remove css class in html elements. To use NgClass, import NgClass first and then use in templete.

      <!--app.component.ts-->
    import { Component } from '@angular/core';
    import { NgClass } from '@angular/common';
    
    @Component({
      selector: 'app-root',
      imports: [NgClass],
      templateUrl: './app.component.html',
      styleUrl: './app.component.css'
    })
    export class AppComponent {
      title = 'ngApp';
    
      x="active";

    }    
  
      <!--app.component.html-->

    <h1>{{title}}</h1>

    <p [ngClass]="x">Paragraph</h1>
    
  

Component Directive

Components directive are directives used with a template. Component directives are the most common directive type in Angular.