What is a Directive in Angular?
A directive is an Angular feature used to change the behavior, appearance, or structure of HTML elements.
Directives work directly with elements in the DOM.
Types of Directives
-
Component Directive – A directive with its own template.
@Component({...}) -
Attribute Directive – Changes the appearance or behavior of an element.
<p [ngClass]="myClass">Hello</p>Examples:
ngClass,ngStyle -
Structural Directive – Changes the DOM structure by adding or removing elements.
<div *ngIf="isLoggedIn">Welcome</div>Examples:
*ngIf,*ngFor
Modern Angular: Control-flow syntax such as
@ifand@foris now preferred for many cases previously handled by*ngIfand*ngFor.
In simple words:
Directive = Instructions given to an HTML element to change its behavior, appearance, or structure.