View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Directives in Angular Explained with Example

By Rohan Vats

Updated on Feb 18, 2025 | 6 min read | 5.4k views

Share:

What are Directives in Angular?

HTML attributes that enable angular to make changes in the style and behaviour of the Dom elements are termed as Directives. Directives can be explained as the building blocks of Angular Applications.

Let us find out what the different types of Directives are:

1. Components

 Directives with a template are called Components.

2. Structural Directives

A directive that can alter the DOm layout by adding and eliminating DOM components.

3. Attribute Directives

A directive that can bring about change in other directives, components or appearance, and behavior of an element is called Attribute Directives.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Component Directives

In Angular Modules, Directives must be declared the same way as components. Component directives are the only directive type that has templates.

Component Directives are decorated with @component decorator.

In any angular project, it is the most commonly used directive.

The syntax to create Component is:

ng generate component <component_name>  or ng g component <component_name>

Component Directive has a structural design and working pattern of how a component is processed. The directives can be defined by using a rich HTML-like syntax. This is because you are inserting HTML directly into the DOM rather than modifying the DOM via APIs.

Structural Directives

A Structural Directive is used to change the Dom layout design and structure. They are mainly used to manipulate and make run time changes in the Dom elements. You can add, edit and remove elements in the DOM using Structural Derivatives.

An asterisk (*) symbol is a distinctive sign of structural directives. Their syntax always begins with an Asterisk (*) prefix.

Structural directives work by adding or removing elements from the Dom to change its appearance. The changes made in the DOM using a Structural Derivative are mutated. The added or removed elements are hidden and initialized at run time. One should be aware of the changes that can happen in the final DOM while using Structural Derivatives.

Popular structural directives include:

  • Nglf

Depending on a condition, Nglf is used to create or remove a part of the DOM tree. It is the simplest structure derivative.

Example:  If you want to make the entire DOM appear and disappear, the code is as follows.

<p *ngIf=”true”> Expression true,makes entire DOM Appears.   </p>

<p *ngIf=”false”> Expression true,makes entire DOM Appears.  </p>

  • NgFor

NgFor is used to customize data display. By using repetitive loops, they can be used to display a list of items.

A basic example to list the name of users:

<ul>

  <li *ngFor=”let user of users”>{{ user.name }}</li>

</ul>

  • NgSwitch

NgSwitch is similar to the JavaScript Switch. From several possible elements, NgSwitch can be used to display one element based on a switch condition.

Example: If there is more than one way to show the same view, the code is as follows:

<container-element [ngSwitch]=”switch_expression”>

  <!– the same view can be shown in more than one case –>

  <some-element *ngSwitchCase=”match_expression_1″>…</some-element>

  <some-element *ngSwitchCase=”match_expression_2″>…</some-element>

  <some-other-element *ngSwitchCase=”match_expression_3″>…</some-other-element>

  <!–default case when there are no matches –>

  <some-element *ngSwitchDefault>…</some-element>

</container-element>

Attribute Directives

Angular developers can use Attribute directives to change the appearance of the element or enhance the functionality. In essence, it can be defined as a Directive decorator annotated class where what changes you want can be specified and what CSS event you wish to bring about that change.

Attribute Directive is usually used in accordion, dropdowns, and tabs. However, to achieve the same level of functionality for recurring elements, you can implement one initially and share it across components.

Some examples of Attribute Directives include:

  • When the user hovers over a specific word, the definition or explanation is showed
  • Highlighting the text.

For an Attribute directive to work, they need access to the DOM and modify it. The three ways to make this happen are:

  • ElementRef
  • Renderer
  • Hostbinding 

ElementRef of the element can be accessed by the Attribute Directives. Likewise, the nativeElement can be accessed using the ElementRef instance in the DOM. But one should make sure the nativeElement is defined, as Angular does not consistently execute within the context of a browser.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Attribute Directive, although it changes the appearance of a DOM element, it looks like a regular HTML attribute. It can be implemented simply by specifying the selector. Directive behavior can be implemented on the controller class.

Example:

If you want to change the color of the text to red when the cursor is hovering over it and black when it is not.

import { Directive, ElementRef, HostListener } from ‘@angular/core’;

@Directive({

  selector: ‘[highlight-text]’

})

export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @HostListener(‘mouseenter’) onMouseEnter() {

        this.el.nativeElement.style.backgroundColor = ‘red’;

  }

  @HostListener(‘mouseleave’) onMouseLeave() {

     this.el.nativeElement.style.backgroundColor = ‘black’;

  }

}

 Attribute directives built into the Angular Framework include:

  • NgStyle

NgStyle can be used to set Dynamic styles depending on the component state. By binding to NgStyle, many inline styles can be simultaneously set.

Example:

To change the background colour to blue, the code would be:

<div [ngStyle]=”{‘background-color’:’blue’}”></<div>

Another example to show the dynamic nature of NgStyle would be:

Set the background color to blue if the user’s country is US and green if it is not. The code would be as follows:

<div [ngStyle]=”{‘background-color’:person.country === ‘US’ ? ‘blue’ : ‘green’ }”></<div>

  • NgClass:

By adding dynamic CSS classes, NgClass can be used to control the appearance of elements. Three types of expression, “return VAlues” are supported by nGclass. They are String, Array, And Object.

Example:

In a table of data, when the value is larger than 100, the text colour should be blue and the text color should be black when the value is less than 100. The code for the above example would be:

<td [ngClass]=”val > 100 ? ‘blue’ : ‘black'”>{{ val }}</td>

Imagining how a directive works and implementing it might seem daunting. But directives are the best way to work on an Angular app, especially if you want to incorporate an interactive UI element into your app. 

We hope this article has provided you with an insight into directives in Angular.

If you would like to learn in-depth about directives and other concepts in Angular, we recommend upGrad’s Executive PG Program in Software Development offered by IIIT Bangalore that comprises five specializations, including Full Stack Development, DevOps, Blockchain Development, Cloud Backend Development, and Big Data Programming. 

The 13-months course is designed by world-class industry professionals and faculty for building competence in industry-relevant tools and software like Python, JavaScript, Angular, etc.

The program offers 360-degree built-in placement support from upGrad career guidance counselors that has helped over 40,000 paid learners secure lucrative jobs at top companies. upGrad’s learner base resides in over 85 countries worldwide, providing enough networking opportunities for students to pursue high-end collaboration projects.

Don’t wait! Book your seat in the program today!

Frequently Asked Questions (FAQs)

1. Should you learn Angular in 2022? Is Angular currently in demand?

2. Can you learn Angular without knowledge of JavaScript?

3. How do components and directives differ from each other?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad KnowledgeHut

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks