Angular Components Created: 06 Jan 2026 Updated: 06 Jan 2026

Switch Control Flow

1. Defining the Data Structure

First, we ensure our data model is strictly typed. Using an interface allows us to define specific categories for our courses.

course-list.component.ts


export interface Course {
id: number;
title: string;
category: 'Development' | 'Design' | 'Marketing' | 'Management';
}

@Component({
selector: 'app-course-list',
standalone: true,
templateUrl: './course-list.component.html',
styleUrl: './course-list.component.css'
})
export class CourseListComponent {
courses: Course[] = [
{ id: 1, title: 'Advanced .NET Microservices', category: 'Development' },
{ id: 2, title: 'Figma for Developers', category: 'Design' },
{ id: 3, title: 'Growth Hacking 101', category: 'Marketing' },
{ id: 4, title: 'Soft Skills for Leads', category: 'Management' }
];
}

2. Implementing @switch with Text Labels

Instead of using emojis, we will use text-based labels. This is often preferred in enterprise applications for better clarity and accessibility.

course-list.component.html


<div class="course-container">
@for (course of courses; track course.id) {
<div class="course-card">
@switch (course.category) {
@case ('Development') {
<span class="badge dev">SOFTWARE DEVELOPMENT</span>
}
@case ('Design') {
<span class="badge design">UI/UX DESIGN</span>
}
@case ('Marketing') {
<span class="badge marketing">DIGITAL MARKETING</span>
}
@default {
<span class="badge general">GENERAL TRAINING</span>
}
}

<h3 class="course-title">{{ course.title }}</h3>
</div>
} @empty {
<p>No courses found matching your criteria.</p>
}
</div>

4. Modern @switch vs. Legacy [ngSwitch]

If you are upgrading from an older version of Angular, you might be used to the [ngSwitch] directive. The new @switch block is a significant upgrade:

FeatureLegacy [ngSwitch]Modern @switch
SyntaxAttribute-based ([ngSwitch], *ngSwitchCase)Built-in block syntax (@switch, @case)
PerformanceHigher overhead (directive-based)Zero-overhead (compiler-optimized)
Type CheckingLimited template type checkingFull integration with TypeScript types
SetupRequires CommonModule importAvailable globally in standalone components


Share this lesson: