Angular Directives
Angular Directives
Angular directives are classes with a @Directive
decorator. Directives are a core feature in Angular that allow you to create custom behavior for elements and components. They can change the structure of the DOM or change the way component and elements behave.
Angular provides three types of directives:
- Component Directives - These are essentially components, the most common type of directive in Angular. Components manage a view and its associated logic.
- Structural Directives - They change the structure of the DOM (e.g., adding/removing elements).
- Attribute Directives - They change the appearance or behavior of an element, component, or another directive.
Below are five examples illustrating different Angular directives:
1. Component Directive:
A component in Angular is a directive with a template. Here's a basic example:
import { Component } from '@angular/core';
@Component({
selector: 'app-sample',
template: `<h2>Welcome to the sample component!</h2>`
})
export class SampleComponent { }
Usage:
<app-sample></app-sample>
2. Structural Directive: *ngIf
This directive adds or removes an element from the DOM based on a condition.
Usage:
<p *ngIf="true">This will be displayed because the condition is true.</p>
3. Structural Directive: *ngFor
This directive instantiates a template once per item from an iterable.
Usage:
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
In the component:
items = ['Item 1', 'Item 2', 'Item 3'];
4. Attribute Directive: [ngClass]
This directive dynamically binds one or more CSS classes to an HTML element.
Usage:
<div [ngClass]="{active: isActive, disabled: !isActive}">Content here</div>
In the component:
isActive = true; // This will apply the 'active' class but not 'disabled'
5. Attribute Directive: [ngStyle]
This directive allows you to set inline styles dynamically.
Usage:
<div [ngStyle]="{'font-size': fontSize + 'px'}">Resize me!</div>
In the component:
fontSize = 16;
Conclusion
Angular directives are powerful tools that can alter the behavior and appearance of elements and components in your application. They provide a declarative approach to managing DOM and component behavior, making your Angular apps more modular and maintainable. Whether you're altering the structure of your application, conditionally rendering content, or simply changing styles, Angular directives are an essential tool in your Angular toolkit.