Angular 18 @switch, @case and @default Example
This is a short guide on angular 18 @switch example. we will help you to give an example of angular 18 switch case example. This article goes in detailed on angular 18 @switch @case example. We will use angular 18 conditional @switch example.
Angular provides conditional statements using ngSwitch, ngSwitchCase, and ngSwitchDefault but, Angular 18 changed the condition statement flow with new syntax. You can use @switch, @case, and @default for the switch case condition in angular 18. You can see one be one example with output and a new conditional statement.
Let's see the simple example code:
Example:
You can update the following code with the app.component.ts file:
src/app/app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
type:number = 2;
}
Here, update the app.component.html file:
src/app/app.component.html
<div class="container">
<!-- Using @switch @case -->
@switch (type) {
@case (1) {
<div>One</div>
}
@case (2) {
<div>Two</div>
}
@default {
<div>Default</div>
}
}
<!-- Using ngSwitch with ngSwitchCase -->
<div [ngSwitch]="type">
<div *ngSwitchCase="1">One</div>
<div *ngSwitchCase="2">Two</div>
<div *ngSwitchDefault>Default</div>
</div>
</div>
Output:
You will see the following output:
Two
Two
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Angular 18 CRUD Application Tutorial Example
- How to Create a Project with App Module in Angular 18?
- Angular 18 Chart JS using ng2-charts Example
- How to Get Current Route in Angular 18?
- Angular 18 Install Font Awesome Icons Example
- How to Integrate Google Maps in Angular 18?
- Angular 18 Stripe Payment Integration Example
- Angular 18 Login with Google Gmail Account Example
- Angular 18 Pagination with NGX Pagination Example
- Angular 18 HttpClient & Http Services Tutorial
- Angular 18 RxJS Observable with Httpclient Example
- How to Define Global Variables in Angular 18?
- Angular 18 Template Driven Form with Validation Example
- Angular 18 Multiple Image Upload Example Tutorial
- Angular 18 File Upload Tutorial Example