Angular directives are classes that allow developers to extend the functionality of HTML elements by modifying their behavior or structure. Directives can manipulate the DOM by dynamically adding or removing elements, applying styles, handling events, or creating reusable components.
What are Angular directives?
Angular provides tools for creating dynamic web applications. A key feature that sets Angular apart from other frameworks is its use of directives, which allow developers to extend HTML syntax and create reusable, dynamic components.
Key takeaways:
Angular directives are powerful tools that allow developers to manipulate the DOM and extend HTML’s capabilities by adding behaviors or changing the structure.
There are three types of directives in Angular:
Component directives: Define views and application logic.
Structural directives: Modify the DOM layout, such as
*ngIfand*ngFor.Attribute directives: Change the behavior or appearance of elements, like
ngClassandngStyle.Built-in directives such as
*ngIf,*ngFor, andngClassare commonly used and provide efficient ways to handle DOM manipulation and styling.Custom directives can be created to encapsulate reusable functionality across an application, making development faster and more maintainable.
Directives help developers in creating dynamic, efficient, and reusable components in their applications.
Keep directives simple, reuse built-in directives, and ensure custom directives are modular and reusable.
What is a directive in Angular?
Directives are HTML attributes. It is essentially a class that can modify the structure of the DOM or change its behavior. It gives the ability to attach additional behaviors to elements in the DOM, such as applying conditional rendering, manipulating the DOM structure, or modifying styles.
Directives are declared using a @Directive decorator and can be applied directly to DOM elements. Directives can modify elements, handle events, or add functionality to components.
Types of directives in Angular
There are three types of Angular directives:
Component directives
Structural directives
Attribute directives
Let’s learn the types of directives in detail.
Component directives
Component directives are the most common type of directives in Angular. Every component is essentially a directive with a template. They define their view and logic, allowing for the modularization of an Angular application. Component directives specify how the component should be processed, instantiated, and used at runtime, forming the core of the application structure.
<h2>Component Directives</h2>
<p>Name string: {{name}}</p>In the above code, we import the Component decorator from the @angular/core package and then use the @Component decorator to define the AppComponent class as a component in Angular. The decorator provides metadata that tells Angular how to create and manage the component, including its selector (how it will be used in templates) and the template URL (where the HTML for the component is located).
Structural directives
Structural directives add or remove the elements from the DOM. Therefore, they are responsible for changing the structure of the DOM. They affect the structure of the view by applying or removing elements based on conditions. The most commonly used structural directives are *ngIf, *ngFor, and *ngSwitch.
*ngIf: It conditionally renders elements based on the result of an expression.
<p *ngIf="isVisible"> This text is conditionally rendered </p>
*ngFor: It is used to loop through arrays and render elements dynamically.
<ul><li *ngFor="let item of items"> {{ item }} </li></ul>
*ngSwitch: It is useful when multiple possible views depend on a single expression.
<div [ngSwitch]="day"><p *ngSwitchCase="'Monday'"> Start of the week! </p><p *ngSwitchCase="'Friday'"> Almost weekend! </p><p *ngSwitchDefault> Any other day </p></div>
Let’s run the following application to see the structural directives in action.
<h2>Structural Directives Example</h2>
<div>
<h3>Available Books</h3>
<p>Here is the list of available books</p>
<ul>
<ng-container *ngFor="let book of books">
<li *ngIf="book.available">
{{ book.name }}
</li>
</ng-container>
</ul>
</div>
<div>
<h3>Unavailable Books</h3>
<p>Here is the list of unavailable books</p>
<ul>
<ng-container *ngFor="let book of books">
<li *ngIf="!book.available">
{{ book.name }}
</li>
</ng-container>
</ul>
</div>
In the above code:
Line 7: We use an
<ng-container>to iterate over thebooksarray with the*ngFordirective.Line 8: We use the
*ngFor="let book of books"to create a loop for each book in thebooksarray. Inside the loop, the*ngIfdirective checks ifbook.availableistrue. If so, the book’s name is displayed in a list item (<li>).Lines 19–20: Similarly, we use the
<ng-container>again and uses*ngForto loop through thebooks. The*ngIfdirective checks ifbook.availableisfalse(!book.available). If true, the book’s name is displayed.
Attribute directives
Attribute directives are used to show or hide elements, apply a conditional style, or dynamically change a component’s behavior according to a changing property. They are applied as attributes to the elements and can be used to change styles or listen to events. The most well-known attribute directive is ngClass, which dynamically adds or removes classes based on an expression.
ngClass: It dynamically assigns CSS classes to elements based on conditions.
<p [ngClass]="{'highlight': isActive, 'inactive': !isActive}"> Text with dynamic classes </p>
ngStyle: It is used to modify styles dynamically based on conditions.
<p [ngStyle]="{'background': isRed ? 'red' : 'green'}"> This is an Attribute Directive</p>
In the code above, we add a red background if the value of the isRed variable is true. If the value of the isRed variable is false, the background of the above elements will be green.
.highlight {
background-color: yellow; /* Example style */
color: black; /* Example style */
}
.inactive {
background-color: lightgray; /* Example style */
color: darkgray; /* Example style */
}
In the app.component.ts file:
Lines 10–11: We create two properties:
isActive: A boolean property that determines if the paragraph is in the active state. It is initialized tofalse.isRed: Another boolean property that determines the background color of the paragraph. It is initialized totrue.
Lines 14–16: We define the
toggleActive()method. This method toggles theisActiveproperty. When called, it switches the value betweentrueandfalse.Lines 19–21: We define the
toggleColor()method, which toggles the value of theisRedproperty betweentrueandfalse.
In the app.component.html file:
Line 5: We use the
ngClassbinding to dynamically control the styles of the<p>element. The expression{'highlight': isActive, 'inactive': !isActive}means:If
isActiveistrue, we apply thehighlightclass.If
isActiveisfalse, we apply theinactiveclass.
Line 13: Similarly, we use the
ngStylebinding to dynamically control the background color of the<p>element.
Custom directives
Custom directives are powerful tools to encapsulate behaviors that you want to reuse across the application. You can create custom attribute directives to encapsulate reusable behaviors. For example, creating a directive to change the background color of an element.
import { Directive, ElementRef, Renderer2 } from '@angular/core';@Directive({selector: '[appHighlight]'})export class HighlightDirective {constructor(el: ElementRef, renderer: Renderer2) {renderer.setStyle(el.nativeElement, 'background-color', 'yellow');}}
In the HTML, we can use this directive as an attribute:
<p appHighlight> This text has a yellow background </p>
Best practices for using directives
Keep it simple: Directives should focus on a single responsibility, like modifying styles or handling events.
Use built-in directives: Angular provides powerful built-in directives like
*ngIfand*ngFor. Reuse these whenever possible instead of writing custom logic.Custom directives: If you write custom directives, make them configurable through inputs to ensure they can be reused across multiple components.
Conclusion
Angular directives are one of the most powerful tools in the Angular framework. They allow developers to modify the behavior and appearance of elements in the DOM dynamically. Whether you’re working with built-in directives like *ngIf, *ngFor, or creating custom directives, learning directives will greatly improve the ability to build dynamic, efficient, and reusable components in Angular.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What are Angular directives?
How many directive types are there in Angular?
What are four directives in AngularJS?
What is Angular language directive?
Free Resources