SlideShare a Scribd company logo
1 of 19
ANGULAR DIRECTIVES
(UNIT 3)
Dr. P. Rambabu, M. Tech., Ph.D., F.I.E.
30-May-2022
Unit 3: Directives
Built-in Directives:
• How to use Built-in Directives:
• Types:
 Component Directives
 Structural Directives
 Attribute Directives.
Custom Directives:
• Creating a Custom Attribute Directive
• Creating a Custom Directive with a Component
Built-in Directives
Directives extend the behavior of HTML, enabling you to create custom HTML elements,
attributes, and classes with functionality specific to an application. Angular provides many
built-in directives, which provide the capability to interact with form elements, bind data in a
component to the view, and interact with browser events.
Using Built-in Directives
Much of the Angular functionality that you need to implement in HTML elements is provided
through built-in directives. These directives provide a wide variety of support for Angular
applications. The following sections describe most of the Angular directives, which fall into
three categories:
1. Component: A directive with a template
2. Structural: A directive that manipulates elements in the DOM
3. Attribute: A directive that manipulates the appearance and behavior of a DOM element
Components Directives
Directives in Angular is a .js class, which is declared as @directive. We have 3 directives in
Angular.
A @Component decorator is actually a @Directive decorator extended with template-
oriented features. Whenever Angular renders a directive, it changes the DOM according to
the instructions given by the directive. Directive appears within an element tag similar to
attributes.
Structural Directives
Structural directives alter layout by adding, removing, and replacing elements in DOM.
*ngIf
When this directive is present in an element, that element is added to the DOM if the value
returns true. If the value returns false, then that element is removed from the DOM,
preventing that element from using resources. Here is an example:
<div *ngIf="students.length > 0">
…..
</div
*ngFor
This directive is used to create a copy of a template for each item within an iterable object.
Here is an example:
<div *ngFor="let student of students">
<div>Name: {{student.name}} </div>
</div>
*ngIf
Syntax:
<p *ngIf="condition"> content to render, when the condition is true </p>
app.component.ts
contacts:any = [
{idno:"101",name: "Sravani", email:"sravani@gmail.com"},
{idno:"102",name: "Abhinandan", email:"abhinandan@gmail.com"},
{idno:"103",name: "Maruti", email:"maruti@gmail.com"},
{idno:"104",name: "Kamalesh", email:"kamalesh@gmail.com"}
];
app.component.html
<div *ngIf="contacts.length>0">
<h5 class="text-center text-success">Some Content is there to display</h5>
</div>
*ngIf with else condition:
Syntax:
<div *ngIf="condition; then normal else elseBlock"></div>
<ng-template #normal>
Content to render when condition is true.
</ng-template>
<ng-template #elseBlock>
Content to render when condition is false.
</ng-template>
app.component.ts:
contacts:any = [];
app.component.ts:
<div *ngIf=" contacts.length >0; then fullContent else emptycontent">here is ignored</div>
<ng-template #fullContent>
<h3 class="text-center text-success">Some content is thre in declared variable</h3>
</ng-template>
<ng-template #emptycontent>
<h3 class="text-center text-danger">provided variable dont have content</h3>
</ng-template>
*ngFor
This directive works like a loop.
app.component.ts:
contacts:any = [
{idno:"101",name: "Sravani", email:"sravani@gmail.com"},
{idno:"102",name: "Abhinandan", email:"abhinandan@gmail.com"},
{idno:"103",name: "Maruti", email:"maruti@gmail.com"},
{idno:"104",name: "Kamalesh", email:"kamalesh@gmail.com"}
];
app.component.html:
<table class="table">
<thead>
<th>Id No</th>
<th>Name</th>
<th>Email</th>
</thead>
<tbody>
<tr *ngFor="let contact of contacts">
<td> {{contact.idno}} </td>
<td> {{contact.name}}
</td>
<td> {{contact.email}} </td>
</tr>
</tbody>
</table>
ngSwitch
This directive displays a template based on the value passed in it. As with ngIf, if
the value does not match the case, the element is not created. Here is an example:
<div [ngSwitch]=“student">
<span *ngSwitchCase = “ ‘Mohan’ “ > Hello Mohan </span>
<span *ngSwitchCase = “ ‘Vijay’ “ > Hello Vijay </span>
<span *ngSwitchDefault > Hello Student </span>
</div>
The ngSwitch directive relies on two other directives to work:
ngSwitchCase and ngSwitchDefault. These directives are be explained below.
ngSwitchCase:
This directive evaluates the value it has stored against the value passed into
ngSwitch and determines whether the HTML template it is attached to should be
created.
ngSwitchDefault:
This directive creates the HTML template if all the above ngSwitchCase
expressions evaluate to false. This ensures that some HTML is generated no
Attribute Directives
Angular attribute directives modify how HTML elements look and behave. They are injected
straight into the HTML and dynamically modify how the user interacts with an HTML
segment. Attribute directives are so named because they often look like normal HTML
attributes.
ngModel
This directive watches a variable for changes and then updates display values based on
those changes. Consider these examples:
app.component.html:
<input type="text" name="data" [(ngModel)]="data" />
<p> {{ data }} </p>
app.component.ts:
ngStyle
This directive updates the styles of an HTML element.
app.component.html:
Example 1:
<div class="col-md-4" [ngStyle]="{'background-color':'green'}">Hello</div>
Example 2:
<div [ngStyle]="{'background-color’: country === 'UK' ? 'yellow' : 'red' }">
{{country}}</div>
app.component.ts:
country:any= 'UK’;
utput:
ngClass
It controls the appearance of elements by adding and removing CSS classes
dynamically.
app.component.html:
<div [ngClass]=“ {'text-primary': country === 'UK’}” > {{country}} </div>
app.component.ts:
country:any= 'UK’;
output:
UK
ngForm
This directive creates a form group and allows it to track the values and validation
within that form group. By using ngSubmit, you can pass the form data as an
object to the submission event. Here is an example:
app.component.html:
<form #formName="ngForm" (ngSubmit)="onSubmit(formName)"> </form
Custom Directives
Creating a custom directive is just like creating an Angular component. To create a custom
directive we have to replace @Component decorator with @Directive decorator.
So, let's get started with creating our first Custom Attribute directive. In this directive, we
are going to highlight the selected DOM element by setting an element’s background color.
Procedure:
Step 1: Create Custom Directive ‘appHighlight’
ng generate directive appHighlight
Step 2: Add below code in appHighlight.ts
Step 3: Add below code in app.component.html
<h1 appAppHighlight > Highlight Me !</h1>
import { Directive, ElementRef } from '@angular/core';
constructor(private eleRef: ElementRef) {}
ngOnInit() {
this.eleRef.nativeElement.style.backgroundColor = "green";
this.eleRef.nativeElement.style.color = "blue";
}
Dr. Rambabu Palaka
Professor
School of Engineering
Malla Reddy University, Hyderabad
Mobile: +91-9652665840
Email: drrambabu@mallareddyuniversity.ac.in
Reference:
Node.js, MongoDB and Angular Web Development
by Brad Dayley, Brenden Dayley, Caleb Daley

More Related Content

What's hot

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

What's hot (20)

JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of Angular
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Angular
AngularAngular
Angular
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Angular 8
Angular 8 Angular 8
Angular 8
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Angular components
Angular componentsAngular components
Angular components
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 

Similar to Angular Directives

Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 

Similar to Angular Directives (20)

AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
Unit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptxUnit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptx
 
mean stack
mean stackmean stack
mean stack
 
Directives
DirectivesDirectives
Directives
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
AngularJS
AngularJSAngularJS
AngularJS
 
Angular2
Angular2Angular2
Angular2
 
Introduction to Angular Js
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular Js
 
GDG Atlanta - Angular.js Demo and Workshop
GDG Atlanta - Angular.js Demo and WorkshopGDG Atlanta - Angular.js Demo and Workshop
GDG Atlanta - Angular.js Demo and Workshop
 
Introduction to single page application with angular js
Introduction to single page application with angular jsIntroduction to single page application with angular js
Introduction to single page application with angular js
 
Angular Directive.pptx
Angular Directive.pptxAngular Directive.pptx
Angular Directive.pptx
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Get rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directivesGet rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directives
 
Angular presentation
Angular presentationAngular presentation
Angular presentation
 

More from Malla Reddy University

More from Malla Reddy University (20)

Unit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxUnit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptx
 
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptxUnit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
 
Unit 1 - Statistics (Part 1).pptx
Unit 1 - Statistics (Part 1).pptxUnit 1 - Statistics (Part 1).pptx
Unit 1 - Statistics (Part 1).pptx
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
GIS - Project Planning and Implementation
GIS - Project Planning and ImplementationGIS - Project Planning and Implementation
GIS - Project Planning and Implementation
 
Geo-spatial Analysis and Modelling
Geo-spatial Analysis and ModellingGeo-spatial Analysis and Modelling
Geo-spatial Analysis and Modelling
 
GIS - Topology
GIS - Topology GIS - Topology
GIS - Topology
 
Geographical Information System (GIS)
Geographical Information System (GIS)Geographical Information System (GIS)
Geographical Information System (GIS)
 
Introduction to Maps
Introduction to MapsIntroduction to Maps
Introduction to Maps
 
Fluid Mechanics - Fluid Dynamics
Fluid Mechanics - Fluid DynamicsFluid Mechanics - Fluid Dynamics
Fluid Mechanics - Fluid Dynamics
 
Fluid Kinematics
Fluid KinematicsFluid Kinematics
Fluid Kinematics
 
Fluid Mechanics - Hydrostatic Pressure
Fluid Mechanics - Hydrostatic PressureFluid Mechanics - Hydrostatic Pressure
Fluid Mechanics - Hydrostatic Pressure
 
Fluid Mechanics - Fluid Pressure and its measurement
Fluid Mechanics - Fluid Pressure and its measurementFluid Mechanics - Fluid Pressure and its measurement
Fluid Mechanics - Fluid Pressure and its measurement
 
Fluid Mechanics - Fluid Properties
Fluid Mechanics - Fluid PropertiesFluid Mechanics - Fluid Properties
Fluid Mechanics - Fluid Properties
 
Reciprocating Pump
Reciprocating PumpReciprocating Pump
Reciprocating Pump
 
E-waste Management
E-waste ManagementE-waste Management
E-waste Management
 
Biomedical Waste Management
Biomedical Waste ManagementBiomedical Waste Management
Biomedical Waste Management
 
Hazardous Waste Management
Hazardous Waste ManagementHazardous Waste Management
Hazardous Waste Management
 
Digital Elevation Model (DEM)
Digital Elevation Model (DEM)Digital Elevation Model (DEM)
Digital Elevation Model (DEM)
 
Introduction to Solid Waste Management
Introduction to Solid Waste ManagementIntroduction to Solid Waste Management
Introduction to Solid Waste Management
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Angular Directives

  • 1. ANGULAR DIRECTIVES (UNIT 3) Dr. P. Rambabu, M. Tech., Ph.D., F.I.E. 30-May-2022
  • 2. Unit 3: Directives Built-in Directives: • How to use Built-in Directives: • Types:  Component Directives  Structural Directives  Attribute Directives. Custom Directives: • Creating a Custom Attribute Directive • Creating a Custom Directive with a Component
  • 3.
  • 4.
  • 5.
  • 6. Built-in Directives Directives extend the behavior of HTML, enabling you to create custom HTML elements, attributes, and classes with functionality specific to an application. Angular provides many built-in directives, which provide the capability to interact with form elements, bind data in a component to the view, and interact with browser events. Using Built-in Directives Much of the Angular functionality that you need to implement in HTML elements is provided through built-in directives. These directives provide a wide variety of support for Angular applications. The following sections describe most of the Angular directives, which fall into three categories: 1. Component: A directive with a template 2. Structural: A directive that manipulates elements in the DOM 3. Attribute: A directive that manipulates the appearance and behavior of a DOM element
  • 7. Components Directives Directives in Angular is a .js class, which is declared as @directive. We have 3 directives in Angular. A @Component decorator is actually a @Directive decorator extended with template- oriented features. Whenever Angular renders a directive, it changes the DOM according to the instructions given by the directive. Directive appears within an element tag similar to attributes.
  • 8. Structural Directives Structural directives alter layout by adding, removing, and replacing elements in DOM. *ngIf When this directive is present in an element, that element is added to the DOM if the value returns true. If the value returns false, then that element is removed from the DOM, preventing that element from using resources. Here is an example: <div *ngIf="students.length > 0"> ….. </div *ngFor This directive is used to create a copy of a template for each item within an iterable object. Here is an example: <div *ngFor="let student of students"> <div>Name: {{student.name}} </div> </div>
  • 9. *ngIf Syntax: <p *ngIf="condition"> content to render, when the condition is true </p> app.component.ts contacts:any = [ {idno:"101",name: "Sravani", email:"sravani@gmail.com"}, {idno:"102",name: "Abhinandan", email:"abhinandan@gmail.com"}, {idno:"103",name: "Maruti", email:"maruti@gmail.com"}, {idno:"104",name: "Kamalesh", email:"kamalesh@gmail.com"} ]; app.component.html <div *ngIf="contacts.length>0"> <h5 class="text-center text-success">Some Content is there to display</h5> </div>
  • 10. *ngIf with else condition: Syntax: <div *ngIf="condition; then normal else elseBlock"></div> <ng-template #normal> Content to render when condition is true. </ng-template> <ng-template #elseBlock> Content to render when condition is false. </ng-template> app.component.ts: contacts:any = []; app.component.ts: <div *ngIf=" contacts.length >0; then fullContent else emptycontent">here is ignored</div> <ng-template #fullContent> <h3 class="text-center text-success">Some content is thre in declared variable</h3> </ng-template> <ng-template #emptycontent> <h3 class="text-center text-danger">provided variable dont have content</h3> </ng-template>
  • 11. *ngFor This directive works like a loop. app.component.ts: contacts:any = [ {idno:"101",name: "Sravani", email:"sravani@gmail.com"}, {idno:"102",name: "Abhinandan", email:"abhinandan@gmail.com"}, {idno:"103",name: "Maruti", email:"maruti@gmail.com"}, {idno:"104",name: "Kamalesh", email:"kamalesh@gmail.com"} ];
  • 12. app.component.html: <table class="table"> <thead> <th>Id No</th> <th>Name</th> <th>Email</th> </thead> <tbody> <tr *ngFor="let contact of contacts"> <td> {{contact.idno}} </td> <td> {{contact.name}} </td> <td> {{contact.email}} </td> </tr> </tbody> </table>
  • 13. ngSwitch This directive displays a template based on the value passed in it. As with ngIf, if the value does not match the case, the element is not created. Here is an example: <div [ngSwitch]=“student"> <span *ngSwitchCase = “ ‘Mohan’ “ > Hello Mohan </span> <span *ngSwitchCase = “ ‘Vijay’ “ > Hello Vijay </span> <span *ngSwitchDefault > Hello Student </span> </div> The ngSwitch directive relies on two other directives to work: ngSwitchCase and ngSwitchDefault. These directives are be explained below. ngSwitchCase: This directive evaluates the value it has stored against the value passed into ngSwitch and determines whether the HTML template it is attached to should be created. ngSwitchDefault: This directive creates the HTML template if all the above ngSwitchCase expressions evaluate to false. This ensures that some HTML is generated no
  • 14. Attribute Directives Angular attribute directives modify how HTML elements look and behave. They are injected straight into the HTML and dynamically modify how the user interacts with an HTML segment. Attribute directives are so named because they often look like normal HTML attributes. ngModel This directive watches a variable for changes and then updates display values based on those changes. Consider these examples: app.component.html: <input type="text" name="data" [(ngModel)]="data" /> <p> {{ data }} </p> app.component.ts:
  • 15. ngStyle This directive updates the styles of an HTML element. app.component.html: Example 1: <div class="col-md-4" [ngStyle]="{'background-color':'green'}">Hello</div> Example 2: <div [ngStyle]="{'background-color’: country === 'UK' ? 'yellow' : 'red' }"> {{country}}</div> app.component.ts: country:any= 'UK’; utput:
  • 16. ngClass It controls the appearance of elements by adding and removing CSS classes dynamically. app.component.html: <div [ngClass]=“ {'text-primary': country === 'UK’}” > {{country}} </div> app.component.ts: country:any= 'UK’; output: UK ngForm This directive creates a form group and allows it to track the values and validation within that form group. By using ngSubmit, you can pass the form data as an object to the submission event. Here is an example: app.component.html: <form #formName="ngForm" (ngSubmit)="onSubmit(formName)"> </form
  • 17. Custom Directives Creating a custom directive is just like creating an Angular component. To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element’s background color. Procedure: Step 1: Create Custom Directive ‘appHighlight’ ng generate directive appHighlight
  • 18. Step 2: Add below code in appHighlight.ts Step 3: Add below code in app.component.html <h1 appAppHighlight > Highlight Me !</h1> import { Directive, ElementRef } from '@angular/core'; constructor(private eleRef: ElementRef) {} ngOnInit() { this.eleRef.nativeElement.style.backgroundColor = "green"; this.eleRef.nativeElement.style.color = "blue"; }
  • 19. Dr. Rambabu Palaka Professor School of Engineering Malla Reddy University, Hyderabad Mobile: +91-9652665840 Email: drrambabu@mallareddyuniversity.ac.in Reference: Node.js, MongoDB and Angular Web Development by Brad Dayley, Brenden Dayley, Caleb Daley