Guest Post

How To Manipulate And Create Directives In Angular?

Table of Contents

What is the Directive?

Directives are mostly used to manipulate the DOM (Document Object Model). By using this, you can define your own directives, change the behavior, layout, appearance of the document object model components. Angular Directives is a TypeScript class which is declared as a @directive decorator. 

@Directive:

@Directive decorator is used for the defining class as an angular directive. We can define the directive to specify the custom appearance with the DOM.

@Directive({
selector?: string
inputs?: string[]
outputs?: string[]
host?: {...}
providers?: Provider[]
exportAs?: string
queries?: {...}
})

@Directive decorator and metadata properties: 

  • Selector: Selector property is used to identify the directive in the HTML template.
  • Inputs: This property is used for input properties for the directive.
  • Outputs: It is used to enumerates the set of event-bound output properties.
  • Providers: It is used to inject any providers for components or services.
  • exportAs: It is used to define the name of the directives which can be used in the template to assign this directive to a variable.
  • Queries: It is used to configure the queries that will be injected into directives. 

Types of Directives: 

There are mainly three types of directives in Angular:

  • Component Directive: Directives with own template.
  • Attribute Directives: Modify the behavior or appearance of the DOM.
  • Structural Directives: Change the DOM by adding and removing elements.

Component Directive:

Component directives are used in the main class. You cannot create an Angular application without one. A component directive requires a view along with its attached behavior. This type of directive connects DOM elements.

The naming convention for the component is name.component.ts.

Attribute Directive: 

The Attribute directive is used to modify the behavior of the DOM element or component. There are two built-in attribute directives in angular: ngStyle and ngClass

ngStyle: NgStyle attribute is used to change the element appearance and behavior. We can set the styles using the ngStyle directive.

<div [ngStyle] ="{ 'background-color' : 'red' }"></div>

This sets the background color of the div to red.

Step 1: ngstyle.component.ts file, we can declare an array of the data.


import { Component, OnInit } from '@angular/core';

@Component({
selector: ‘app-ngstyle’,
templateUrl: ‘./ngstyle.component.html’,
styleUrls: [‘./ngstyle.component.scss’]
})
export class DirectiveComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
people: any[] = [
{
“name”: “Keval Patel”,
“country”: ‘India’
},
{
“name”: “Mcleod Mueller”,
“country”: ‘USA’
},
{
“name”: “Aniket Badrakiya”,
“country”: ‘UK’
},
{
“name”: “Neel Patel”,
“country”: ‘India’
},
{
“name”: “Cook Tyson”,
“country”: ‘USA’
},
{
“name”: “Vishal Rathod”,
“country”: ‘India’
}
];
}

Step 2: Create an HTML view to display the data.

NgStyle
  • {{ person.name }} ({{ person.country }})
  • Structural Directives:

Structural directives start with * sign. These directives are handling the structure and layout of the component or the element renders in a template.

There are three structural directives accessible in angular:

  • NgIf (*ngIf)
  • NgFor (*ngFor)
  • NgSwitch (*ngSwitch)

NgIf: The NgIf directive is used when you desire to display or truncate a component based on a few conditions.

Syntax:  *ngIf= “<condition>”

Let’s take a look at an example of ngIf:

import { Component, OnInit } from '@angular/core';

@Component({
selector: ‘app-ngstyle’,
templateUrl: ‘./ngstyle.component.html’,
styleUrls: [‘./ngstyle.component.scss’]
})
export class DirectiveComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
people: any[] = [
{
“name”: “Keval Patel”,
“age”: 35
},
{
“name”: “Purvi Barot”,
“age”: 25
},
{
“name”: “Aniket Badrakiya”,
“age”: 20
},
{
“name”: “Neel Patel”,
“age”: 45
},
{
“name”: “Meha Patel”,
“age”: 26
},
{
“name”: “Vishal Rathod”,
“age”: 50
}
];
}

NgIf

  • {{ person.name }} ({{ person.age }})

NgFor: NgFor directive is used for the changes in the structure of the DOM.

Syntax: *ngFor = “let item of items”

NgIf

  • {{ person.name }} ({{ person.age }})

NgSwitch: NgSwitch directive is used to display one or more DOM elements based                           on condition.

ngSwitch contains three separate directives: ngSwitch, ngSwitchCase, ngSwitchDefault.

Let’s take a look of an example:

import { Component, OnInit } from '@angular/core';

@Component({
selector: ‘app-ngstyle’,
templateUrl: ‘./ngstyle.component.html’,
styleUrls: [‘./ngstyle.component.scss’]
})
export class DirectiveComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
people: any[] = [
{
“name”: “Keval Patel”,
“age”: 35,
“country”: ‘India’
},
{
“name”: “Purvi Barot”,
“age”: 25,
“country”: ‘USA’
},
{
“name”: “Aniket Badrakiya”,
“age”: 20,
“country”: ‘India’
},
{
“name”: “Neel Patel”,
“age”: 45,
“country”: ‘UK’
},
{
“name”: “Neha Patel”,
“age”: 26,
“country”: ‘USA’
},
{
“name”: “Vishal Rathod”,
“age”: 50,
“country”: ‘Canada’
}
];
}

NgIf

  • {{ person.name }} ({{ person.country }})
  • {{ person.name }} ({{ person.country }})
  • {{ person.name }} ({{ person.country }})
  • {{ person.name }} ({{ person.country }})

 

How to create Custom Directive? 

Let’s start to create a simple custom directive.

Go to your project directory and execute the below command to create a custom directive:

ng g directive Highlight

After executing this command, created two files in the project – src/app folder

highlight.directive.ts

highlight.directive.spec.ts

Let’s see the sample code file:

Highlight.ts file

import { Directive } from '@angular/core';

@Directive({
selector: ‘[appHighlight]’
})
export class HighlightDirective {
constructor() { }

}

After that we need to import this file into app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from ‘./app-routing.module’;
import { AppComponent } from ‘./app.component’;
import { NgstyleComponent } from ‘./ngstyle/ngstyle.component’;
import { HighlightDirective } from ‘./highlight.directive’;

@NgModule({
declarations: [
AppComponent,
NgstyleComponent,
HighlightDirective
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Conclusion:

In programming language, like a function you can write the code and later you can call it anytime whenever you want etiquette of that function. Correspondingly, you can generate a directive and write the behavior inside it. Then, wherever you have requirement of that behavior, you can import the directive.


Ajay Patel – Technical Director, iFour Technolab Pvt. Ltd.

A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. Wish sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at AngularJS Frontend Software Company – iFour Technolab Pvt. Ltd.