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 *ngIf and *ngFor.

    • Attribute directives: Change the behavior or appearance of elements, like ngClass and ngStyle.

  • Built-in directives such as *ngIf, *ngFor, and ngClass are 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

Directive types in Angular
Directive types in Angular

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>
Using component directive in our Angular app

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>
An example of ngSwitch
  • *ngFor: It is used to loop through arrays and render elements dynamically.

<ul>
<li *ngFor="let item of items"> {{ item }} </li>
</ul>
An example of ngSwitch
  • *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>
An example of ngSwitch

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>
Using structural directive in our Angular app

In the above code:

  • Line 7: We use an <ng-container> to iterate over the books array with the *ngFor directive.

  • Line 8: We use the *ngFor="let book of books" to create a loop for each book in the books array. Inside the loop, the *ngIf directive checks if book.available is true. 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 *ngFor to loop through the books. The *ngIf directive checks if book.available is false (!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>
An example of ngClass
  • 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 */
}
Using attribute directive in our Angular app

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 to false.

    • isRed: Another boolean property that determines the background color of the paragraph. It is initialized to true.

  • Lines 14–16: We define the toggleActive() method. This method toggles the isActive property. When called, it switches the value between true and false.

  • Lines 19–21: We define the toggleColor() method, which toggles the value of the isRed property between true and false.

In the app.component.html file:

  • Line 5: We use the ngClass binding to dynamically control the styles of the <p> element. The expression {'highlight': isActive, 'inactive': !isActive} means:

    • If isActive is true, we apply the highlight class.

    • If isActive is false, we apply the inactive class.

  • Line 13: Similarly, we use the ngStyle binding 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');
}
}
Creating custom directives in Angular

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 *ngIf and *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?

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.


How many directive types are there in Angular?

There are three main types of directives in Angular:

  • Component directives: These define views and application logic.
  • Structural directives: These modify the DOM structure, such as *ngIf and *ngFor.
  • Attribute directives: These change the behavior or appearance of elements, like ngClass and ngStyle.

What are four directives in AngularJS?

In AngularJS, some of the commonly used directives include:

  • ngModel: Binds input fields to model data.
  • ngRepeat: Iterates over an array to create multiple elements.
  • ngIf: Conditionally displays an element based on an expression.
  • ngClass: Dynamically assigns CSS classes to elements.

What is Angular language directive?

The Angular language directive generally refers to the ability to influence the behavior or appearance of HTML elements based on conditions, events, or other logic. These directives, such as *ngFor, *ngIf, and custom directives, allow developers to interact with the DOM and create dynamic, data-driven applications.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved