Open In App

@switch in angular 17

Last Updated : 18 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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_STRUCTURE
Project Structure

Updated 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:

Output

The @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:

Output
Output

ngSwitch 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.

Next Article
Article Tags :

Similar Reads