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
@if in Angular 17 Angular continues to evolve with each release. Angular 17 introduces various new features aimed at enhancing the developer experience and simplifying the framework's overall functionality. One such feature is the addition of the @if directive, which streamlines how developers handle conditional rend
5 min read
Style Binding in Angular 17 In Angular, creating visually appealing and dynamic user interfaces is important for delivering an engaging user experience. One such powerful feature is Style Binding. It allows you to dynamically apply CSS styles to HTML elements based on component data or expressions. In this article, we'll explo
2 min read
Updates in Angular 12 Angular 12 is the latest version of the popular front-end web development framework. Angular released in May 2021 comes with several new features and improvements that enhance the performance, productivity, and stability of the framework. In this article, we will see different key features and impro
5 min read
Using ngx-webstorage with Angular 17 Using ngx-webstorage with Angular 17 offers an easy approach to using the power of the browser's Web Storage API within your Angular applications. This article will guide you through the process of integrating ngx-webstorage, a dedicated library for Angular that simplifies client-side data persisten
3 min read
Angular 17 Angular, the popular JavaScript framework, continues its journey of updation with the release of version 17, bringing some new improvements, and new features, as well as some breaking changes and deprecations. Table of Content What's new in Angular 17?Major Changes in Angular v17Deprecations in Angu
7 min read