Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Directives in Angular Explained with Example

Updated on 30 November, 2022

5.32K+ views
6 min read

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.

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?

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.

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

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

RELATED PROGRAMS