Built-in directives in Angular
Last Updated :
28 Mar, 2024
Directives are markers in the Document Object Model(DOM). Directives can be used with any controller or HTML tag which will tell the compiler what exact operation or behavior is expected. There are some directives present that are predefined but if a developer wants he can create new directives (custom-directive).
There are basically 3 types of directives and each type has some built-in directives. In this article, we will discuss all 3 types of directives and their built-in directives.
1. Component Directives
Components are directives with templates. They are the building blocks of Angular applications, encapsulating both the UI (User Interface) and the behavior of a part of the application. Components are used to create reusable and modular UI elements. They are declared using the @Component decorator and typically have a corresponding HTML template.
Syntax: In the component below, we have used the @Component here to define a component.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {}
2. Attribute Directives
Attribute directives are used to change the appearance or behavior of a DOM element by applying custom attributes. These directives are applied to elements as attributes and are denoted by square brackets. Attribute directives are often used for tasks such as dynamic styling, input validation, or DOM manipulation.
Built-in Attribute Directives:
1. ngClass: The NgClass directive allows us to conditionally apply CSS classes to HTML elements.
Syntax:
<div [ngClass]="{'class-name': condition}">
<!-- Content here -->
</div>
2. ngStyle: The NgStyle directive enables you to conditionally apply inline styles to HTML elements.
Syntax:
<div [ngStyle]="{'property': 'value'}">
<!-- Content here -->
</div>
3. ngModel: The NgModel directive provides two-way data binding for form elements, syncing data between the model and the view.
Syntax:
<input [(ngModel)]="property">
Example:
HTML
<!-- app.component.html -->
<div class="container">
<h1 class="title">GeeksforGeeks</h1>
<div class="content">
<div [ngClass]="{'highlight': isHighlighted, 'italic': isItalic}">
This div's classes are dynamically applied based on conditions.
</div>
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">
This div's styles are dynamically applied based on properties.
</div>
<input type="text" [(ngModel)]="username" class="input-field">
<p class="greeting">Hello, {{ username }}!</p>
</div>
</div>
CSS
/* app.component.css */
.container {
text-align: center;
}
.title {
color: green;
}
.content {
margin-top: 20px;
}
.input-field {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
.greeting {
margin-top: 20px;
}
JavaScript
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isHighlighted: boolean = true;
isItalic: boolean = false;
textColor: string = 'blue';
fontSize: number = 18;
username: string = '';
}
JavaScript
//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:

3. Structural Directives
Structural directives are responsible for manipulating the DOM layout by adding, removing, or manipulating elements based on conditions. They are denoted by an asterisk (*) preceding the directive name and are commonly used to alter the structure of the DOM based on conditions. Examples include , , and ngSwitch.
Built-in Attribute Directives:
1. ngIf: The ngIf directive conditionally includes or removes an element based on a provided expression.
Syntax:
<element *ngIf="condition">
<!-- Content to display when condition is true -->
</element>
2. ngFor: The ngFor directive iterates over a collection and instantiates a template once for each item in the collection.
Syntax:
<element *ngFor="let item of items">
<!-- Content to repeat for each item -->
</element>
3. ngSwitch: The ngSwitch directive is similar to a switch statement in programming languages. It displays one element from a set of elements based on a provided expression.
Syntax:
<element [ngSwitch]="expression">
<element *ngSwitchCase="value1"> <!-- Content for case 1 -->
</element>
<element *ngSwitchCase="value2"> <!-- Content for case 2 -->
</element>
<!-- More ngSwitchCase elements for other cases -->
<element *ngSwitchDefault> <!-- Default content -->
</element>
</element>
Example:
HTML
<!-- app.component.html -->
<div class="container">
<h1 class="title">GeeksforGeeks</h1>
<div class="content">
<div *ngIf="isLoggedIn" class="message">
Welcome to {{ username }}!
</div>
<ul *ngIf="items.length > 0" class="list">
<li *ngFor="let item of items" class="list-item">
{{ item }}
</li>
</ul>
<div [ngSwitch]="color" class="color-switch">
<p *ngSwitchCase="'red'" class="color-message">Red color selected</p>
<p *ngSwitchCase="'blue'" class="color-message">Blue color selected</p>
<p *ngSwitchCase="'green'" class="color-message">Green color selected</p>
<p *ngSwitchDefault class="color-message">Please select a color</p>
</div>
</div>
</div>
CSS
/* app.component.css */
.container {
text-align: center;
}
.title {
color: green;
}
.content {
margin-top: 20px;
}
.message {
font-size: 20px;
color: green;
margin-bottom: 20px;
}
.list {
list-style-type: none;
padding: 0;
}
.list-item {
font-size: 16px;
margin-bottom: 5px;
}
.color-switch {
margin-top: 20px;
}
.color-message {
font-size: 18px;
margin-top: 10px;
}
JavaScript
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isLoggedIn: boolean = true;
username: string = 'GFG';
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
color: string = 'red';
}
Output:

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. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
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
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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ 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
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
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read