With Angular 17, a new template syntax known as @switch was added, which enables the display or hiding of template portions based on logical conditions.
The former ngSwitch structural directive has been replaced with this new syntax.
What is @switch?
The @switch template syntax is used to select the appropriate template section to render based on the value of an expression; it is similar to the switch statement in JavaScript for Angular programming. Depending on the expression's value, you should usually use @switch when you have at least two or more alternatives to display. However, you normally want to use the @if syntax if you have only two alternatives to display.
The syntax of the @switch template is not a directive, as you can see. Like @if or @for, this function is directly integrated into the template engine.
When to Use @switch?
When there are several options to show depending on a single condition, use @switch. In general, the @if syntax is more suitable when you have just two options.
Example of @switch with Multiple @case Blocks
Set Up a New Angular Project
- Install the Angular CLI globally:
npm install -g @angular/cli
- Create a new Angular project:
ng new <YOUR_PROJECT_NAME>
- Open the directory for your project:
cd <YOUR_PROJECT_NAME>
Project Structure:
Project StructureUpdated Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"lodash": "^4.17.21",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example: This example shows the use of switch.
HTML
<!-- app.component.html -->
@switch (color) {
@case ("red") {
<div style="background-color: red; color: aliceblue; height: 30px;">Red</div>
}
@case ("green") {
<div style="background-color: green; color: aliceblue; height: 30px;">green</div>
}
}
JavaScript
<!-- app.component.ts -->
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'if-directive';
color = "green";
}
Explanation:
Class property:
- title: A string containing the application's title.
- color: This property has an initial value of "green" and is used to identify which HTML block should be rendered in the template's @switch directive.
app.component.html
- @switch: The value of the color property is assessed by this directive. Though intended for direct use in Angular templates, it resembles the conventional JavaScript switch statement.
- @case: Every @case block indicates a potential color value. The appropriate block of HTML will be rendered if the color property matches the string given in the @case.
- In the first @case, the color "red" is checked. Should this be the case, a <div> with a red background and the text "Red" styled with color: aliceblue will be rendered.
- In the second @case, the color "green" is checked. If this is accurate, a <div> with a green background and the text "Green" styled in a similar way will be rendered.
Output:
OutputThe @default clause in @switch
The @switch directive:
- The color property defined in the AppComponent class is evaluated by the @switch directive. It enables you to render various template parts according to that value.
- This is comparable to a JavaScript switch statement, in which the value of an expression controls how the code is executed.
@case Blocks:
- Every @case block represents a possible color property value
- The corresponding HTML block will be shown when color matches the value entered in a @case.
- For example:
- The first @case block will run if the color is "red," displaying a <div> with the text "Red" and a red background.
- The second @case block will run if the color is "blue," displaying a <div> with the text "Blue" and a blue backdrop.
Block by default:
- Any color value that does not match the designated @case values is handled by the @default block as a backup.
- If color is neither "red" nor "blue," the @default block will run, displaying a <div> with the text "Default" and a yellow background. This is helpful for handling undefined or unexpected values in a courteous manner.
HTML
@switch (color) {
@switch (color) {
@case ("red") {
@case ("red") {
<div style="background-color: rgb(253, 45, 8);
color: aliceblue; height: 30px;">Red</div>
<div style="background-color: rgb(253, 45, 8);
color: aliceblue; height: 30px;">Red</div>
}
}
@case ("blue") {
@case ("blue") {
<div style="background-color: rgb(4, 0, 253);
color: aliceblue; height: 30px;">Blue</div>
<div style="background-color: rgb(4, 0, 253);
color: aliceblue; height: 30px;">Blue</div>
}
}
@default {
@default {
<div style="background-color: rgb(255, 247, 0);
color: rgb(0, 0, 0); height: 30px;">Default</div>
<div style="background-color: rgb(255, 247, 0);
color: rgb(0, 0, 0); height: 30px;">Default</div>
} }
JavaScript
<!-- app.component.ts -->
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'if-directive';
color = "green";
}
Output:
OutputngSwitch vs @switch
- An Angular directive for condition-based UI rendering is called ngSwitch.
- A structural directive that allows views to be dynamically switched depending on the value of an expression.
- Probably connected to TypeScript or other customized implementations, @switch is not a typical Angular feature.
- For example, when you define methods or properties in a class, @switch is usually associated with TypeScript decorators.
Similar Reads
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
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
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
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network
A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read