Understanding the Difference Between Structural/Template and Regular Directives in Angular
Dec 19, 2019 • 12 Minute Read
Introduction
Angular is popular among front-end frameworks and JavaScript-based libraries due to its single-page application behavior and the model view controller approach.
With each new version of Angular, the team has added various new features, but one core feature remains the same, called the directive.
The Directive in Angular
The directive in Angular, one of the most widely used features, is an instruction to the DOM; in other words, we can say that directives are the kind of decorators that mark a class or component as a directive.
There are some in-built directives, and we can also create custom directives to attach some custom behavior to the different elements.
Angular supports a total of three types of directives:
- Component directives
- Structural directives
- Attribute directives
These directives can be used to change the behavior or appearance of DOM elements by applying inline properties along with the appropriate values.
In this guide, we are going to learn about the difference between component directives and structural directives. We'll save attribute directive for another guide.
Before we dig into the difference, let's look closer at each of the two directives, that is, component and structural directives, and how they work in the application.
Component Directive
The component directive is one of the most common directives and is used throughout into the application. Hence, no Angular application can be complete without the component directive.
The component directive is a class with the @Component decorator attached. We know that the Angular application should have at least one component, the root component. So the component directive is must-have in every application.
It is used to attach the template and styles along with the component class, and it gives us a flexible way to define components along with the template and stylesheets.
Since it is a component directive, the other two types of directives, structural and behavioral directives, are just made to modify the behavior of the DOM elements only.
Let’s create an Angular app by using the below ng command.
Ng new directivesdemo
After creating the Angular app, it will create a root component by default called app, and the folder will contain three different files:
-
App.component.ts: This contains all the business logic for the same component class as well as various properties and methods to control the behavior of the template.
-
App.compoinent.html: This contains the complete HTML markup logic, which will be controlled from the component. It’s not compulsory to specify the template source code into the separate file; we can also specify template code into the component directly.
-
App.component.css: This contains the necessary CSS stylesheet for the component, which is connected to the component via style attribute. As in HTML, we can also specify styles into the component directly instead of specifying into the separate CSS file.
These three files are an integral part of any component in the application. Thus we can redesign the structure by specifying CSS and HTML code into the component file itself.
Now let’s open the component app.component.ts file, and the source code will look like this.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor() {
}
}
Here in this component file, @Component is a decorator that is always attached to the class to add its behavior. There are three terms in which components can create.
-
Selector: The selector is a unique identifier for each component, and if we want to render any other component, then we can use their selector name so that it will be presented as a child component into the parent component.
-
TemplateUrl: The template URL is used to specify the file in which we can define our template code, and the URL of the template will be controlled from the component.
-
StyleUrl: Style URL is used to specify the file of the stylesheet where we can write the styles that can apply to the template, which is connected to the specific component.
This is how we can create the component by specifying @Component decorator along with the template and style URL.All of them act as a single unit, which is called a component.
Structural Directive
Structural directives are used to manipulate the DOM behavior only.
More specifically, we can say that structural directives are used to create or destroy the different DOM elements, that is, to add, modify, or delete any element permanently from the DOM tree.
Before using a structural directive, we must know and be careful that it creates or eradicates the element from the DOM and updates the DOM frequently, so we may have to think twice before applying the business logic to them.
In Angular, structural directives are divided into three different types:
- NgIf
- NgFor
- NgSwitch
These three elements are used to hide elements conditionally, add multiple elements into DOM, and render any specific element based on the condition.
All of the structural directives can recognize by asterisk sign (*).
Let’s learn the basics of these three types of structural directives.
NgIf Directive
The ngIf directive is the most straightforward structural directive and is used to show or hide any element from the DOM conditionally.
It is pretty similar to the if-else condition when we can provide the specific situation. If the condition can be satisfied, the element is rendered, or else we can render any default element if the condition is false.
Let’s look at the NgIf directive and how it works by using a simple example.
Create the component and open the file called ngifdirective.component.ts and paste the following lines of source code.
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-ng-if-directive",
templateUrl: "./ng-if-directive.component.html",
styleUrls: ["./ng-if-directive.component.css"]
})
export class NgIfDirectiveComponent implements OnInit {
// Boolean variables
isDivVisible: boolean = true;
isLabelVisible: boolean = false;
constructor() {}
ngOnInit() {}
}
Here we have two different boolean variables, isDivVisible and isLabelVisible, along with the default value, and these values will be used in the template to show or hide any elements from the DOM.
The next step is to open the file ngifdirective.component.html and paste the following lines of source code.
<div>
<span>Ng-if Directive example</span><br/><br/>
<div *ngIf='isDivVisible'>
This DIV is visible using ngIf condition
</div>
<label *ngIf='isLabelVisible'>
This label is hidden based on ngIf condition
</label>
</div>
We have two different elements into the template, which are div and a label control, and along with the control, we have used *ngIf directive followed by the variable name.
So based on the condition, if the answer is correct, then it will show the element. Otherwise, it will hide the element from the DOM.
NgFor directive
The ngfor directive is used to iterate the values of the array, which is similar to the for loop, which we use in a different programming language.
Let’s create a new component and open the file called ngfordirective.component.ts and paste the following lines of code.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ng-for-directive',
templateUrl: './ng-for-directive.component.html',
styleUrls: ['./ng-for-directive.component.css']
})
export class NgForDirectiveComponent implements OnInit {
employees: any = [
'employee 1',
'employee 2',
'employee 3',
'employee 4',
'employee 5',
]
constructor() { }
ngOnInit() {
}
}
Here the one variable that is important to notice is the employees variable, which is an array of the different objects which we are going to iterate into the template file called ngfordirective.component.html.
<ul>
<li *ngFor="let emp of employees">{{ emp }}</li>
</ul>
We have an element called <ul>, and inside the unordered list, we need to iterate the array of items using the for loop.
So along with the <li> element, the additional property has been used, *ngFor, which accepts the array, and each of the items will be rendered until it reaches the last value in the collection.
We can also make use of index along with the item, like this.
<ul>
<li *ngFor="let emp of employees; let i=index">{{ emp }} {{ i }}</li>
</ul>
NgSwitch directive
The ngSwitch directive is very similar to the switch case, and it is used to render the element based on the single condition followed by the different case statements.
Let’s create a new component and open the file ngSwitchDirective.component.ts and paste the following lines of code.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ng-switch-directive',
templateUrl: './ng-switch-directive.component.html',
styleUrls: ['./ng-switch-directive.component.css']
})
export class NgSwitchDirectiveComponent implements OnInit {
age: number = 25;
constructor() { }
ngOnInit() {
}
}
We have one variable called age along with the default value, and this variable will be used into the template to render a specific element which satisfies the condition.
Open the file ngSwwitchdirective.component.html and paste the following lines of code.
<div [ngSwitch]="age">
<span *ngSwitchCase="55">Your age is > 50</span>
<span *ngSwitchCase="45">Your age is > 40</span>
<span *ngSwitchCase="35">Your age is > 30</span>
<span *ngSwitchCase="25">Your age is > 20</span>
<span *ngSwitchCase="15">Your age is > 10</span>
</div>
The parent <div> element holds the condition, which is age, and based on the condition we have different cases using *ngSwitchCase.
As soon as the condition remains true, the related element will be rendered into the DOM, and the rest of the items will be ignored.
Comparing Component and Structural Directives
The component directive is just a directive that attaches the template and style for the element, along with the specific behavior. The structural directive modifies the DOM element and its behavior by adding, changing, or removing the different elements.
omponent directives use the @Component decorator and require a separate view for the component, while structural directives are inbuilt in Angular and only focus on the DOM elements.
A component directive can be created multiple times, that is, every component in Angular will have a @Component decorator attached, while we cannot apply more than one structural directive to the same HTML element.
So these are the differences between component and structural directives. One thing to keep in mind that one is being used for attaching a class to the directive, and the other is used to play with the DOM elements.
Conclusion
In this guide, you learned about directives and why they are essential for an Angular application. Then we went through the different types of directives supported in Angular.
Component structural directives are very different in every aspect because the component directive is attached to every component, which requires view, while structural directives can be applied to the elements to modify DOM elements.
Stay tuned for more advanced guides, and keep reading.