Angular directives are attributes or elements in Angular that attach special behavior to the DOM (Document Object Model) elements. They extend HTML by allowing you to create new HTML elements or attributes with custom behaviors. Angular directives can be used to manipulate the DOM, style elements, bind data to the view, and manage interactions between components.
There are three types of Angular directives:
1. **Component Directives**: These are custom directives that allow you to create new HTML elements or components with encapsulated behavior. Components are essentially directives that have a template bound with data.
2. **Attribute Directives**: These directives are used to modify the behavior, appearance, or state of a DOM element. They are defined in the form of HTML attributes and can be applied to any HTML element.
3. **Structural Directives**: These directives are responsible for manipulating the structure of the DOM by adding, removing, or manipulating elements. Generally, they are used for modifying the layout by adding or removing DOM elements.
Here are a few built-in directives in Angular:
1. ‘ngIf‘: A structural directive that conditionally includes a template based on the value of an expression. It adds or removes the DOM element based on the truthiness of the provided expression.
Example:
<div *ngIf="isLoggedIn">Welcome, User!</div>
2. ‘ngFor‘: A structural directive that iterates over a collection and instantiates a template for each item in the collection.
Example:
<li *ngFor="let item of items">{{ item.name }}</li>
3. ‘ngSwitch‘: A structural directive that conditionally swaps the contents of a container by adding or removing DOM elements based on a given condition.
Example:
<div [ngSwitch]="userType">
<div *ngSwitchCase="'admin'">Hello, Admin!</div>
<div *ngSwitchCase="'user'">Hello, User!</div>
<div *ngSwitchDefault>Hello, Guest!</div>
</div>
4. ‘ngClass‘: An attribute directive that dynamically adds or removes CSS classes to a DOM element based on a given expression.
Example:
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">{{ item.name }}</div>
5. ‘ngStyle‘: An attribute directive that dynamically sets CSS styles to a DOM element based on a given expression.
Example:
<div [ngStyle]="{'width': widthInPercentage + '%', 'color': textColor }">{{ item.name }}</div>
6. ‘ngModel‘: An attribute directive that provides two-way data binding between the view and the model. It is mainly used with form elements.
Example:
<input [(ngModel)]="user.name" />
These are just a few examples of built-in directives available in Angular. Directives are an essential part of Angular applications and provide a powerful way to create reusable and flexible UI components, manipulate the DOM, and manage the presentation logic.