Angular 17 added new control flow statements and loops like @for block, @if block and @switch block. In this post we'll see how to use @switch block in Angular with examples.
@switch block in Angular
If you have a lot of conditions doing equality checks then using @switch case, rather than @if block, provides better readability.
@switch block control flow syntax conditionally renders a content block based on the value of an expression. It displays the content block depending on which @case matches the evaluated expression. It is inspired by switch statement in JavaScript.
Syntax of @switch block in Angular is as given below-
@switch (expression) {
@case (valueA) {
//Case A block
}
@case (valueB) {
//Case B block
}
@default {
// Default block
}
}
@switch (expression): This initiates the switch-case statement, where expression is the value that will be compared against the various cases.
@case (value): Inside the @switch block there can be many @case statements, with each @case specifying a value. If the expression strictly equals a value in a @case, the content within that @case block is rendered.
@default: If none of the @case values match the expression, the content within the @default block is rendered. This is an optional block, if no @default block exists and no @case matches, nothing is displayed.
Note that, @switch does not have a fallthrough, if a @case matches the expression, its content is rendered, and flow comes out of the @switch block without going to any other @case or @default block. You do not need break or return statements.
This new @switch block tries to do away with the verbose structure of the ngSwitch Directive in Angular.
@switch block Angular example
In the example there is a component where an array is initialized and a method that returns the length of the array.
switchdemo.component.ts
import { Component } from "@angular/core";
@Component({
selector: 'app-switchdemo',
standalone: true,
templateUrl: './switchdemo.component.html'
})
export class SwitchdemoComponent {
numArray: number[];
constructor(){
this.numArray = [1, 2, 3];
}
getLength() : number{
return this.numArray.length;
}
}
In the template there is a switch block that uses the returned length as an expression and renders a message based on the current length of the array.
switchdemo.component.html
<h2>Switch Demo</h2>
@switch(getLength()){
@case(0){
<p>No number is added</p>
}
@case(1){
<p>One number is added</p>
}
@case(2){
<p>Two numbers are added</p>
}
@case(3){
<p>Three numbers are added</p>
}
@default{
<p>More than three numbers are added</p>
}
}
That's all for this topic @switch in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Angular Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment