Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconDirectives in Angular Explained with Example

Directives in Angular Explained with Example

Last updated:
28th Jun, 2022
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
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.

Ads of upGrad blog

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:

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

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.

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.

Ads of upGrad blog

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!

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1Should 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.

2Can 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.

3How 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.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6085
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas &#038; Topics
12777
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions &#038; Answers [For Freshers &#038; Experienced]
5676
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions &#038; Answers in US [2024]
5397
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas &#038; Topics For Beginners [US 2023]
11006
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5460
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5560
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5042
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5534
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon