Directives in Angular
In Angular, directives are a powerful tool that allows you to manipulate the DOM (Document Object Model) and add dynamic behavior to your HTML templates. Essentially, they are classes that extend HTML functionality, enabling you to create more interactive and personalized user interfaces.
Structural Directives
Structural directives in Angular are used to modify the DOM structure, allowing you to add, remove, or manipulate view elements dynamically. These directives directly affect the application flow and are represented with an asterisk (*) in the template code.
*ngIf
allows you to show or hide elements based on a boolean condition. For example, if we want to display a message only when a variable is true, we would use:
<p *ngIf="usuarioAutenticado">Welcome, user</p>
*ngFor
allows you to iterate over a list of elements, generating a dynamic representation based on the data. It is used as follows:
<li *ngFor="let item of lista">{{ item }}</li>
*ngSwitch
is used to display a different view based on the value of a variable. It works similarly to a "switch" control structure in JavaScript.
Attribute Directives
Attribute directives in Angular allow you to modify the appearance or behavior of an element without altering its structure in the DOM. They are applied directly to HTML attributes and can change dynamically in response to events or state changes.
ngClass
is used to apply CSS classes conditionally. For example, we can change the color of a button based on the state of a variable:
<button [ngClass]="{ 'btn-success': activo, 'btn-danger': !activo }">Status</button>
ngStyle
allows you to dynamically modify inline styles. We can change the color of a paragraph based on a variable:
<p [ngStyle]="{ 'color': activo ? 'green' : 'red' }">Example text</p>
Custom Directives
Angular allows us to create our own custom directivesto encapsulate reusable behaviors in different components. A custom directive is a TypeScript class decorated with@Directive
and can interact with HTML elements in the template.
For example, if we want to create a directive that changes the background color of an element on hover, we can define it as follows:
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appResaltar]' }) export class ResaltarDirective { constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.style.backgroundColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.el.nativeElement.style.backgroundColor = 'transparent'; } }
Then, this directive can be used simply by addingappResaltar
to any HTML element within an Angular template:
<p appResaltar>Hover over this text</p>