Structural and Attribute Directives

Overview

Among Angular's many features, two core concepts stand out: structural and attribute directives. In this article, we will explore these directives in depth to help you understand how they enhance Angular's capabilities.

Structural Directives

Structural directives in Angular are responsible for altering the structure of the DOM (Document Object Model). They are used to conditionally add, remove, or manipulate elements within the HTML markup. Angular offers several built-in structural directives, with *ngIf and *ngFor being the most commonly used.

*ngIf

The *ngIf directive is used to conditionally display or remove an element from the DOM based on the truthiness of an expression. It effectively toggles the element's presence based on whether the expression to true or false. This is particularly useful for showing or hiding elements dynamically.

<div *ngIf="userLoggedIn">Welcome, {{ username }}!</div>

In this example, the div element will only be rendered if the userLoggedIn expression evaluates to true . If userLoggedIn is false, the element will not appear in the DOM.

*ngFor

The *ngFor directive is employed to iterate over a collection, such as an array, and generate elements for each item in the collection. This is invaluable for rendering dynamic lists and tables.

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

Here, *ngFor iterates through the items array and generates a li element for each item, resulting in a list of items.

Attribute Directives

While structural directives manipulate the DOM's structure, attribute directives in Angular are used to modify the appearance or behavior of an element. They do so by adding, modifying, or removing attributes or classes. Two of the most commonly used attribute directives in Angular are ngStyle and ngClass.

ngStyle

The ngStyle directive allows you to apply dynamic styles to an element based on expressions. It accepts an object where each key is a CSS property, and each value is the corresponding style value.

<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">Styled Text</div>

In this example, the ngStyle directive dynamically sets the color and font-size CSS properties of the div element based on the values of textColor and fontSize.

ngClass

The ngClass directive enables you to dynamically add or remove CSS classes to an element based on expressions. This is particularly useful for conditional styling.

<div [ngClass]="{'active': isActive, 'error': hasError}">Styled Text</div>

Here, the ngClass directive adds the active class when isActive is true and the error class when hasError is true.