Manipulating the DOM with Directives in Angular
Learn how to dynamically control your web page's content, style, and structure with Angular's most powerful feature.
What Are Directives?
In Angular, directives are special instructions in the DOM that tell Angular to do something to a DOM element, such as change its structure, style, or behavior. They are essentially markers on a DOM element which attach a specified behavior to that element.
Structural Directives: Reshaping the DOM
Structural directives change the DOM layout by adding and removing DOM elements. They are easy to recognize because they are prefixed with an asterisk (*). The most common are *ngIf
(to conditionally add/remove an element) and *ngFor
(to repeat an element for each item in a list).
Attribute Directives: Changing Appearance & Behavior
Attribute directives change the appearance or behavior of an element, component, or another directive. They don't add or remove elements. Instead, they modify the element they are attached to. Common examples include ngClass
(to add/remove CSS classes) and ngStyle
(to apply inline styles).
Custom Directives: Creating Your Own
Beyond the built-in directives, Angular allows you to create your own custom directives. This is a powerful feature for encapsulating reusable functionality. You can create a directive that, for example, highlights an element on mouseover or implements custom validation logic on an input.
Practice Zone
Interactive Test 1: Sort the Directives
Drag each directive to its correct category.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build a Dynamic List
Rellena los huecos en cada casilla.
<ul> <li *ngFor="let of "> .name '}} </li> </ul>
Practice Example: Code Editor
Conditionally add the CSS class 'active' to the div if the `isActive` property is true.
Directives in a Real Application
Directives are the workhorses of Angular templates. Here’s how you might combine them to build a dynamic user interface.
1. Rendering a List of Users
You'll almost always use *ngFor
to display data from an API. Here, we loop through a `users` array and create a list item for each one. Notice how we also use *ngIf
to show a fallback message if the array is empty.
<div *ngIf="users.length > 0; else noUsers">
<ul>
<li *ngFor="let user of users">
{{ user.name }}
</li>
</ul>
</div>
<ng-template #noUsers>
<p>No users found.</p>
</ng-template>
2. Dynamic Styling with `ngClass`
Attribute directives allow for powerful, data-driven styling. In this example, we apply different CSS classes to a user's status badge based on their `status` property.
<span [ngClass]="{
'badge-success': user.status === 'active',
'badge-warning': user.status === 'pending',
'badge-danger': user.status === 'inactive'
}">
{{ user.status }}
</span>
3. Creating a Custom "Permissions" Directive
Imagine you need to hide certain buttons based on a user's role. A custom structural directive is perfect for this. It keeps your templates clean and centralizes the permission logic.
<button *appHasRole="'admin'">
Delete User
</button>
// The directive logic (simplified)
@Input() appHasRole: string;
...
if (currentUser.role !== this.appHasRole) {
viewContainer.clear(); // This removes the element
}
Practical Takeaway: Master the combination of structural and attribute directives to create templates that are clean, readable, and dynamically adapt to your application's state.
Angular Directives Glossary
- Directive
- A class in Angular decorated with `@Directive` that can modify the structure, behavior, or style of DOM elements.
- Structural Directive
- A directive that changes the DOM layout by adding, removing, or manipulating elements. Always prefixed with an asterisk (*).
- *ngIf
- A structural directive that conditionally creates or disposes of a part of the DOM tree based on a boolean expression.
- *ngFor
- A structural directive that renders a template for each item in a collection.
- Attribute Directive
- A directive that changes the appearance or behavior of an element. It does not alter the DOM structure.
- ngClass
- An attribute directive that adds or removes a set of CSS classes based on conditions.
- ngStyle
- An attribute directive that adds or removes a set of inline HTML styles based on conditions.
- @Directive
- A decorator that marks a class as an Angular directive and provides configuration metadata.