
Directives in Angular

Table of Contents
- What are Angular Directives?
- Types of Directives in Angular
- Structural Directives
- Attribute Directives
- Structural Directives
- Attribute Directives
- Creating Custom Directives
- Ways to Pass Input to Directives
- Frequently Asked Questions
In the world of Angular, one feature that significantly enhances your web development capabilities is ‘Directives‘. These are unique and powerful tools in Angular’s arsenal, allowing developers to modify HTML behavior in a declarative way. This article aims to demystify directives and illustrate how they can be used to add dynamic functionality to your Angular applications.
What are Angular Directives?
Directives are instructions in the DOM (Document Object Model). Think of them as markers on the HTML elements that tell Angular to run or apply some behavior to that element. In simpler terms, directives are like extra attributes added to your HTML elements, giving them new capabilities.
We are here to help you with Angular Js learning and real-time project based training. Join our Angular JS training in Hyderabad demo and start learning angular course by highly experienced faculty and fully hands-on experience.
Types of Directives in Angular
Angular has three kinds of directives:
Component Directives:
Component directives in Angular are a fundamental concept, acting essentially as directives with a template. Every Angular component is a directive with a view, meaning it controls a part of the screen where Angular renders a template. This allows for modular, reusable pieces of the user interface.
Explore this blog to uncover key facts about Components and Modules in Angular, crucial for any developer.
Example of a Component Directive:
Here’s a simple Angular component that acts as a directive:
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<h1>Hello, {{ name }}!</h1>`
})
export class GreetingComponent {
name = 'Angular User';
}
This component can be used anywhere in an Angular application by simply including <app-greeting></app-greeting>
in the HTML, rendering the greeting “Hello, Angular User!”.
Structural Directives:
Structural directives in Angular alter the DOM’s layout by adding, removing, or manipulating elements. They are essential for dynamic designs where the application interface changes according to the data.
Example of a Structural Directive:
Here’s a basic usage of the *ngFor
directive to iterate over a list of items:
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
import { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
templateUrl: './item-list.component.html'
})
export class ItemListComponent {
items = ['Apple', 'Banana', 'Cherry'];
}
See also: Tech Mahindra React JS Interview Questions
Attribute Directives:
Attribute directives change the appearance or behavior of an element, component, or another directive. They are used for manipulating properties such as styles or classes based on logic defined in the directive.
Example of an Attribute Directive:
Here’s how you might use ngStyle
to dynamically change the style of an element:
<div [ngStyle]="{'font-style': fontStyle, 'font-weight': fontWeight}">
Stylish text!
</div>
import { Component } from '@angular/core';
@Component({
selector: 'app-stylish-text',
templateUrl: './stylish-text.component.html'
})
export class StylishTextComponent {
fontStyle = 'italic';
fontWeight = 'bold';
}
See also: TCS AngularJS Developer Interview Questions
Structural Directives
Structural directives in Angular are powerful tools that change the structure of the DOM, primarily by adding, removing, or manipulating elements. They can significantly alter the layout based on some logic or condition, enabling dynamic rendering of the interface based on user interactions or data changes. Common examples of structural directives include *ngFor
, *ngIf
, and *ngSwitch
.
Boost your Angular expertise by learning interesting facts about State Management in Angular through this comprehensive guide.
Example of a Structural Directive: *ngIf
The *ngIf
directive is used to conditionally include or exclude a DOM element based on the truthiness of an expression. This can be useful for showing or hiding elements based on user inputs, permissions, or other logical conditions.
Here is a simple example demonstrating how to use *ngIf
to conditionally display a message:
<!-- app.component.html -->
<div *ngIf="showMessage">
Welcome to Angular!
</div>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
showMessage = true;
}
In this example:
The <div>
element will only appear in the DOM if showMessage
is true
.
The showMessage
property is defined in the TypeScript file of the component (AppComponent
). If it’s set to true
, the “Welcome to Angular!” message will be displayed. If it’s false
, the <div>
will not be rendered in the DOM.
See also: Flipkart Angular JS interview Questions
Attribute Directives
Attribute directives in Angular are a type of directive used to change the appearance or behavior of DOM elements, components, or even other directives. Unlike structural directives that change the structure of the DOM by adding or removing elements, attribute directives change the properties of existing elements. They can modify attributes, host bindings, or even react to host events to perform tasks.
Attribute directives are commonly used to dynamically alter how an element looks or behaves, such as changing colors, disabling controls, or altering other attributes based on certain conditions.
Example: ngStyle
Directive
One common attribute directive is ngStyle
, which allows you to dynamically set CSS styles on an HTML element. Here’s an example:
<!-- app.component.html -->
<div [ngStyle]="{'background-color': bgColor, 'color': textColor}">
This text has dynamic styles!
</div>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
bgColor = 'lightblue';
textColor = 'darkred';
}
<div [ngStyle]="{'font-size': fontSize + 'px'}"> Text with dynamic font size </div>
In this example:
The ngStyle
directive is used to apply styles dynamically to a <div>
element. The styles are specified in an object with property names corresponding to the CSS properties and values taken from component properties (bgColor
and textColor
).
The bgColor
and textColor
properties are defined in the AppComponent
class. You can change these properties programmatically based on certain conditions, user interactions, or other inputs, and the changes will be reflected in the appearance of the <div>
element.
This blog offers a deep dive into Pipes in Angular—find out what you need to know.
Creating Custom Directives:
Angular not only provides built-in directives but also allows you to create your own custom directives. This is powerful because you can encapsulate complex behavior into reusable directives. For example, you might create a directive that changes the background color of a button when it’s clicked.
Creating a custom directive in Angular allows you to encapsulate reusable behavior into a directive that can be applied to elements in your Angular applications. Below, I’ll guide you through the steps to create a simple custom attribute directive that changes the background color of an HTML element when the user hovers over it. This directive will be called appHighlight
.
Step 1: Generate the Directive
First, you need to generate the directive using Angular CLI. Open your terminal and runs.
ng generate directive highlight
This command creates a new directive in your project called HighlightDirective
, with files for the directive’s code and its associated tests.
Step 2: Implement the Directive
Now, let’s implement the logic for changing the background color on hover. You’ll modify the highlight.directive.ts
file:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]' // Using attribute selector to apply this directive
})
export class HighlightDirective {
@Input() defaultColor: string = 'transparent';
@Input() highlightColor: string = 'yellow';
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = this.defaultColor;
}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor);
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(this.defaultColor);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
How to Set up the Development Environment for Angular Application?
Step 3: Use the Directive in Your Component
With the directive implemented, you can now use it in any component. Open your component’s HTML file and add the appHighlight
attribute to an element. You can also bind input properties to control the colors dynamically:
<!-- app.component.html -->
<p [appHighlight]="true" [defaultColor]="'transparent'" [highlightColor]="'blue'">
Hover over me to see the highlight!
</p>
Explanation:
Directive Definition: The directive is defined with a selector appHighlight
, which means it can be applied as an attribute to any HTML element.
Host Listeners: The @HostListener
decorators add event listeners for mouse enter and mouse leave events, calling the respective methods to change the background color.
Input Properties: The defaultColor
and highlightColor
are input properties that allow the consumer of the directive to specify what colors should be used when the element is not hovered over and when it is.
See also: Beginner AI Interview Questions and Answers
Ways to Pass Input to Directives in Angular
In Angular, directives are a powerful feature that allows you to manipulate the DOM or apply specific behaviors to elements in your application. One of the key functionalities of directives is the ability to pass data or inputs into them, enabling them to operate dynamically based on the input values. There are several ways to pass input to directives, including using input properties and binding values directly in the template.
1. Using @Input() Decorator
The most common way to pass input to a directive is by using the @Input()
decorator. This method allows you to define properties in your directive that can receive values from the parent component. The parent component can then bind values to these properties using Angular’s property binding syntax.
Example: Let’s create a simple directive that changes the background color of an element based on the input value passed from the parent component.
// highlight.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
@Input() appHighlight: string = '';
constructor(private el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
}
Explanation:
The @Input()
decorator is used to define an input property named appHighlight
.
The directive is applied to an element, and the background color is set based on the value passed to the appHighlight
property.
Template Usage:
<p appHighlight="yellow">This text has a yellow background!</p>
<p appHighlight="lightblue">This text has a light blue background!</p>
Here, the appHighlight
directive is used to pass different color values that are applied to the paragraph elements’ backgrounds.
Read this awesome blog on Introduction to Angular to enhance your understanding and skills.
2. Using Aliases with @Input()
In some cases, you might want the directive’s property name to differ from the attribute name used in the template. Angular allows you to create an alias for the @Input()
property, enabling you to bind to the directive using a different name in the template.
Example:
// highlight.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
@Input('color') appHighlight: string = '';
constructor(private el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.style.backgroundColor = this.appHighlight;
}
}
Template Usage:
<p [color]="'green'">This text has a green background!</p>
<p [color]="'pink'">This text has a pink background!</p>
Explanation:
In this example, the @Input('color')
syntax creates an alias for the appHighlight
property, allowing the directive to be used with the color
attribute in the template. This can make your template more intuitive or align with your naming conventions.
Explore this blog to uncover key facts about Data Binding in Angular, crucial for any developer.
3. Using Input with Structural Directives
For structural directives, which change the DOM structure (like *ngIf
or *ngFor
), you can also pass input using @Input()
properties, but with a bit of a twist. Structural directives are prefixed with an asterisk (*
) and can receive input values that dictate their behavior.
Example:
// appRepeat.directive.ts
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appRepeat]'
})
export class RepeatDirective {
@Input('appRepeat') set repeatTimes(times: number) {
this.viewContainer.clear();
for (let i = 0; i < times; i++) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
}
Template Usage:
<p *appRepeat="3">This paragraph is repeated three times.</p>
Explanation:
- In this example, a custom structural directive called
appRepeat
is created. - The
@Input('appRepeat')
decorator allows you to pass a number indicating how many times the element should be repeated. - The directive then dynamically adds the element to the DOM the specified number of times.
Read more about Angular Material and UI Components
4. Passing Multiple Inputs
Sometimes, a directive may need to receive multiple inputs. You can easily do this by defining multiple @Input()
properties within your directive.
Example:
// border.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appBorder]'
})
export class BorderDirective implements OnInit {
@Input() borderColor: string = 'black';
@Input() borderWidth: string = '1px';
constructor(private el: ElementRef) {}
ngOnInit() {
this.el.nativeElement.style.border = `${this.borderWidth} solid ${this.borderColor}`;
}
}
See also: Infosys AngularJS Interview Questions
Template Usage:
<p appBorder borderColor="red" borderWidth="2px">This paragraph has a red border of 2px width.</p>
<p appBorder borderColor="blue" borderWidth="5px">This paragraph has a blue border of 5px width.</p>
Explanation:
- Here, the
appBorder
directive accepts two input properties:borderColor
andborderWidth
. - These properties are used to dynamically set the border style of the element to which the directive is applied.
FAQs
1. What Are Four Directives in AngularJS?
In AngularJS, directives are special tokens in the HTML that tell the AngularJS compiler to do something to a DOM element (like hide it, display a list of elements, etc.). Here are four commonly used directives in AngularJS:
ng-app
: This directive is used to define the root element of an AngularJS application. It automatically initializes the AngularJS framework within the defined scope.ng-model
: Binds the value of HTML controls (input, select, textarea) to application data. It also updates the value in the control if the data changes.ng-repeat
: Repeats a set of HTML elements for each item in a collection. It’s commonly used to generate lists or tables.ng-if
: Conditionally includes or excludes a DOM element based on the truthiness of an expression.
See also: TCS AngularJS Developer Interview Questions
2. What Is an Example of a Directive?
An example of a directive in Angular (not AngularJS) is the *ngIf
directive. This structural directive is used to conditionally include or exclude elements in the DOM based on an expression’s value.
Example:
<p *ngIf="isLoggedIn">Welcome back, user!</p>
<p *ngIf="!isLoggedIn">Please log in to continue.</p>
In this example, the *ngIf
directive is used to check the value of the isLoggedIn
property. If isLoggedIn
is true
, the first paragraph is displayed; if false
, the second paragraph is shown.
Learn more about Angular Material and UI Components
3. What Is ngModel
in Angular?
The ngModel
directive in Angular is used for two-way data binding. It binds the value of an HTML control (such as an input or textarea) to a property on the Angular component’s model, and vice versa. This means any changes in the input field are automatically reflected in the component’s data model, and updates to the model are instantly shown in the view.
Example:
<input [(ngModel)]="userName" placeholder="Enter your name">
<p>Hello, {{ userName }}!</p>
In this example, ngModel
binds the input field to the userName
property of the component. Whatever the user types into the input field is immediately reflected in the userName
variable, and thus displayed in the paragraph below.
See also: Accenture Angular JS interview Questions
4. What Is NgIf
in Angular?
NgIf
is a structural directive in Angular that conditionally includes or removes an element from the DOM based on the truthiness of an expression. If the expression evaluates to true
, the element is included in the DOM; if false
, the element is removed.
Example:
<button (click)="toggleLogin()">Toggle Login</button>
<p *ngIf="isLoggedIn">You are logged in!</p>
<p *ngIf="!isLoggedIn">You are not logged in.</p>
Here, NgIf
is used to display different messages depending on whether the isLoggedIn
property is true or false. Clicking the button toggles the login state and updates the view accordingly.
5. Why Do We Use @NgModule
in Angular?
@NgModule
is a decorator in Angular that is used to define a module. A module in Angular is a container for a cohesive block of code dedicated to a specific application domain, a workflow, or a closely related set of capabilities. The @NgModule
decorator provides metadata that tells Angular how to compile and launch the application, what components, directives, and pipes belong to this module, and what services should be available for injection.
Example:
@NgModule({
declarations: [AppComponent, LoginComponent],
imports: [BrowserModule, FormsModule],
providers: [AuthService],
bootstrap: [AppComponent]
})
export class AppModule { }
In this example, @NgModule
is used to declare the AppModule
class as an Angular module. It lists the components and modules that belong to this module and specifies that the application should start by bootstrapping the AppComponent
.
6. What Is NgForm
and NgModel
?
NgForm
: NgForm
is a directive in Angular that is automatically applied to <form>
elements. It tracks the form’s state and provides various properties and methods to handle form validation, submission, and resetting. It’s a key part of Angular’s forms module, helping manage form control states and validations.
Example:
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<input name="userName" ngModel required>
<button type="submit">Submit</button>
</form>
In this example, NgForm
tracks the state of the form and allows access to the form’s data and validation status through the userForm
reference.
NgModel
: As explained earlier, ngModel
is a directive used for two-way data binding in Angular. It binds an HTML form element to a component property and keeps them in sync.
Example:
<input [(ngModel)]="userName" name="userName">
This binds the userName
property in the component to the input field, allowing for real-time synchronization between the view and the model.
Together, NgForm
and NgModel
are fundamental to handling forms in Angular, providing robust features for managing user input, validation, and form submission.
Read more about Angular forms with code examples.
Directives in Angular provide a unique and powerful way to extend HTML’s capabilities. They allow you to write cleaner, more declarative, and more efficient code by encapsulating complex behaviors into simple HTML-like tags or attributes. Whether you’re using built-in directives like ngIf
and ngFor
or creating your own custom directives, understanding this concept is crucial for any Angular developer. It’s through directives that Angular allows you to build interactive and dynamic web applications with ease and precision.
Angular JS training in Bangalore | Angular JS training in Pune | Angular JS training in Delhi |
Angular JS training in India | Angular JS training in Chennai | Angular JS training in UK |
Angular JS training in Australia | Angular JS training in Ahmedabad | Angular JS training in Noida |