Home Courses Directives - Structural, Attribute & Component Directives

Directives - Structural, Attribute & Component Directives

Angular Directives

In Angular, control flow statements are more recommended in the latest versions, but directives are still an important part of the Angular syllabus and are widely asked in interviews.


Directives are used to change the DOM appearance, behavior, and structure.

Anything visible on the UI is rendered through DOM elements, and directives control how those elements behave and look.


What Are Directives

Directives allow you to:

  1. Show or hide elements
  2. Apply conditions and loops
  3. Change styles and classes
  4. Modify the structure of the DOM

Examples of common directives are ngIf, ngFor, ngStyle, ngClass, and ngSwitch.


Types of Directives

Component Directives

Components themselves are directives.

The @Component decorator makes a class a component directive.

It contains:

  1. selector
  2. template
  3. styles
  4. imports

Because of this, components are also called component directives.


Structural Directives

Structural directives change the structure of the DOM.

They are used for:

  1. conditions
  2. loops
  3. switching templates

Common examples are:

  1. *ngIf
  2. *ngFor
  3. *ngSwitch


Attribute Directives

Attribute directives change the appearance or behavior of elements.

They are mostly used for:

  1. styles
  2. classes

Common examples are:

  1. ngStyle
  2. ngClass


Example of ngIf Directive

A signal is used to check whether a user is logged in.

isLogin = signal(true)

The element is displayed only when the condition is true.

<h1 *ngIf="isLogin()">Welcome User</h1>

If isLogin is false, the heading will not appear.

For directives like ngIf to work, CommonModule must be imported, otherwise errors will appear.


Example of ngFor Directive

A signal is created to store multiple users.

users = signal(["anil", "same", "peter", "bruce"])

*ngFor is used to loop through the users.

<div>
<ul *ngFor="let user of users()">
<li>{{ user }}</li>
</ul>
</div>

Since users is a signal, it is accessed using users().


Example of ngStyle Directive

A normal property is used to store a color.

pColor = "red"

The color is applied using ngStyle.

<p [ngStyle]="{ color: pColor }">Hello visitors</p>

This changes the text color dynamically.

Share this lesson: