Directives in Angular Explained with Example

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.

Types of 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:


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


  • 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>


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.

Popular Courses & Articles on Software Engineering

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.


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’;


  selector: ‘[highlight-text]’


export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @HostListener(‘mouseenter’) onMouseEnter() { = ‘red’;


  @HostListener(‘mouseleave’) onMouseLeave() { = ‘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.


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’ === ‘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.


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!

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

Yes, Angular is a worthy skill to possess in 2022, considering the massive demand for MEAN stack developers at tech giants today. Angular is considered one of the top three favored JavaScript frameworks by developers for full-stack development and front-end development. It is an alternative to React that is technically challenging but provides a more intuitive interface for mobile app development.

Can you learn Angular without knowledge of JavaScript?

No, Angular requires you to have basic knowledge of JavaScript. However, Angular has a moderate learning curve and can be mastered in relatively less time by registering for a short course.

How do components and directives differ from each other?

Component directives are employed to indicate HTML templates and carry a structural design. It is a basic directive in Angular that is processed at runtime. Directives, on the other hand, are indicators of the DOM elements, including attributes, CSS class, comments, etc.

Want to share this article?

Lead the Data Driven Technological Revolution

Leave a comment

Your email address will not be published. Required fields are marked *

Our Best Software Development Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks