- read

Exploring Angular — Part 3: Directives

Șener Ali 92

angular directives
Angular Directives

If you missed the previous article on Data Binding, you can catch up right here: Exploring Angular — Part 2: Data Binding.

What are Angular Directives?

Angular directives are powerful tools that extend the functionality of your HTML templates. They allow you to add dynamic behavior and manipulate the DOM (Document Object Model) within your Angular applications. In essence, directives are like instructions to Angular that tell it how to handle specific elements in your UI.

Types of Angular Directives

Just as we have different types of data binding, Angular directives also come in various flavors. Let’s take a closer look at the two main categories of Angular directives:

1. Structural Directives

Structural directives change the structure of the DOM by adding or removing elements. They are preceded by an asterisk (*) in your HTML code. Some of the most commonly used structural directives in Angular are *ngIf, *ngFor, and *ngSwitch.

For example, *ngIf allows you to conditionally render elements based on a specified expression. This is incredibly handy when you want to show or hide parts of your UI dynamically.

<div *ngIf="isUserLoggedIn">Welcome, {{ userName }}</div>

2. Attribute Directives

Attribute directives modify the appearance or behavior of an element. They don’t change the structure of the DOM but rather add functionality to existing elements. Angular provides several built-in attribute directives like ngStyle, ngClass, and ngModel.

About the ngModel directive, we talked in the previous article. So, we will focus on the ngStyle and ngClass directives.

ngStyle Directive

The ngStyle directive allows you to dynamically apply CSS styles to an element based on the values of properties in your component. Here's an example:

<div [ngStyle]="{ 'font-size.px': fontSize, 'color': fontColor }">Dynamic Styling</div>

In this example, we bind the ngStyle directive to an object that defines the styles to apply. The styles are based on…