Difference between structural and attribute directives
Last Updated :
16 Apr, 2024
Structural directives manipulate the DOM layout by adding, removing, or replacing elements, while attribute directives modify the appearance or behavior of elements without affecting their structure. Directives in Angular are nothing but the classes that allow us to add and modify the behavior of elements. Using directives in angular we can modify the DOM (Document Object Module) styles, handle user functionality, and much more.
There are mainly two types of directives Structural Directives and Attribute Directives. In this article let us learn more about these directives
Structural Directives
In Angular, structural directives are a type of directive that modify the layout of the DOM by adding, removing, or replacing elements based on certain conditions. We have three built-in structural directives namely : *ngIf, *ngFor, *ngSwitch.
Features of Structural Directives :
- Control Rendering: They conditionally render templates based on expressions, allowing you to show or hide content based on certain conditions.
- Iteration: They enable you to loop through collections and generate multiple instances of a template for each item in the list.
- Altering the DOM layout : Structural directives allow us to add or remove elements from DOM based on the truthiness of the expression.
1. *ngIf Directive
This directive helps us to conditionally include or remove elements from the DOM. Using ngIf directive we can create dynamic user interfaces.
Syntax :
*ngIf="Expression"
2. *ngFor Directive
This directive helps us to iterate over Arrays, Objects, Lists etc and display a template for each item in the collection. This is generally and efficient way used to dynamically display the data over the repeated items. This is similar to for loop in our programming languages.
Syntax :
*ngFor="let <item> of Collection"
3. *ngSwitch Directive
This directive helps us to conditionally display an element from different section of elements based on given expression. It is similar to switch case in our programming languages.
Syntax:
<element [ngSwitch]="expression">
<some-element *ngSwitchCase*="value"> Contents... </some-element>
<some-element *ngSwitchCase="value"> Contents... </some-element>
<some-element *ngSwitchCase> Contents... </some-element>
<some-element *ngSwitchDefault>Default value...</some-element>
</element>
Example demonstrating all three structural directives :
HTML
<!-- app.component.html -->
<div *ngIf="showExample">
<p>Programming Languages:</p>
<div *ngFor="let item of items">
<li>item</li>
</div>
<div [ngSwitch]="status">
<p *ngSwitchCase="'active'">Status : Active</p>
<p *ngSwitchCase="'inactive'">Status : Inactive</p>
<p *ngSwitchDefault>Status : Undefined</p>
</div>
</div>
JavaScript
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
items = ['Java', 'Python', 'C'];
status = 'active';
showExample = true;
}
Output:

In the above example, we have seen the usage of *ngIf, *ngFor and *ngSwitch. Using ngIf on `showExample` property, to determine whether to show the content , and iterating over an `items` array using *ngFor, and a `status` property used with *ngSwitch to conditionally display different messages based on its value.
Attribute Directives
In Angular, Attribute directives are used within html tags to modify the appearance of elements, components or directives. They are used for Dynamic Styling, DOM Manipulation etc.
Features of Attribute Directives :
- Dynamic Styling: Attribute directives can be used to dynamically apply styles to HTML elements based on certain conditions.
- DOM Manipulation: They enable you to interact with and manipulate the DOM based on user actions or application state changes.
- Reusability: Attribute directives promote code reuse by encapsulating behavior that can be applied to multiple elements across the application.
- Enhanced Functionality: They allow you to extend HTML with custom functionality, improving the overall user experience.
We have 3 main built in attribute directives: ngClass, ngStyle and ngModel.
1. ngClass
This attribute is used to conditionally give the classes to the elements based on the value binded to ngClass directive.
Syntax:
<element [ngClass]="expression"></element>
2. ngStyle
This attribute is used to dynamically apply the styles to elements based on the value binded to ngStyle directive. It helps us to modify the appearance of elements on conditional basis. We can also use ngStyles to override in
Syntax:
<element [ngStyle]="expression"></element>
3. ngModel
This attribute is generally used to bind form control data to a class variable . This allows a two way binding and this is most commonly used directive with forms. It also comes with few basic validations like required,minLength , maxLength which can be directly used in our input tags.
To use this directive we need to import Forms Module in our module file.
Syntax:
<input name="name" [(ngModel)]="name"/>
Example demonstrating all three attribute directives :
HTML
<!-- app.component.html -->
<form>
<div>
<label>Name: </label>
<input
type="text"
name="name"
minlength="4"
[(ngModel)]="name"
#nameInput="ngModel"
required
[ngClass]="{ 'is-invalid': nameInput.touched && nameInput.invalid }"
/>
<div *ngIf="nameInput.touched && nameInput.invalid">
Minimum length of name is 4 characters
</div>
</div>
<div>
<label>Age: </label>
<input
type="number"
name="age"
[(ngModel)]="age"
#ageInput="ngModel"
required
[ngStyle]="{
'border-color': ageInput.invalid && ageInput.touched ? 'red' : ''
}"
/>
<div *ngIf="ageInput.touched && ageInput.invalid">Age is required</div>
</div>
</form>
JavaScript
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
name: string = '';
age!: number;
}
Output:
.gif)
In this example we have used all the three attribute directives , and displayed the errors using ngClass , ngStyle. We have stored the values of the fields using ngModel .
Differences between structural and attribute directives
Structural Directives | Attribute Directives |
---|
They alter the structure of the DOM by adding , removing or manipulating elements.
| They change the behaviour or appearance of an element, component, or other directive
|
Prefixed with an asterisk (*) in the template.
eg: *ngIf, *ngFor
| Used as attributes in the template.
eg : `[ngClass]`, `[ngStyle]`
|
Used for conditionally displaying elements or iterating over a collection.
| Used for applying dynamic styles, modifying existing behaviour
|
Generally, only one structural directive can be applied to a single element at a time.
| We can combine multiple attribute directives on a single element.
|
Ex : *ngIf, *ngFor, *ngSwitch
| Ex : [ngClass] , [ngStyle] , [ngModel]
|
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read