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"}
];
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