Angular Directives
Written By: Avinash Malhotra
Updated on
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
- Structural
- Attribute
- 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
- NgIf
- NgFor
- 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 AngularNgFor directive
ngFor directive is used to create an element through loop. It is used for Array, Objects and JSON Data.
ngFor in AngularNgSwitch
ngSwitch directive is used to show or hide element based of switch condition.
ngSwitch in AngularAttribute 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
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.