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

IF Control Block

Defining the Data Model

Before building a component, we must define the shape of the data it will handle. Using the Angular CLI, we can generate an interface to ensure type safety across our application.


ng generate interface models/course

In the generated course.ts file, we define our structure. Using interfaces prevents runtime errors by catching type mismatches during development:


// models/course.ts
export interface Course {
id: number;
courseName: string;
category: string;
}

2. Managing Data in the Component

Once the interface is ready, we use it within our component logic. This ensures that our courses array strictly follows the structure we defined.


// course-list.component.ts
import { Component } from '@angular/core';
import { Course } from '../models/course';

@Component({
selector: 'app-course-list',
standalone: true,
imports: [],
templateUrl: './course-list.component.html',
styleUrl: './course-list.component.css',
})
export class CourseListComponent {
listTitle: string = "Available Training Programs";
// Strongly typed array using our Interface
courses: Course[] = [];
}

3. The New Control Flow: @if, @else if, and @else

Angular recently moved away from the structural directive *ngIf in favor of a new, more performant, and readable syntax. This "Control Flow" looks more like standard JavaScript and reduces the need for extra <ng-container> tags.

In your template (course-list.component.html), you can now handle conditional rendering like this:

HTML


<h1>{{ listTitle }}</h1>

@if (courses.length > 0) {
<div class="stats">
<p>Total Courses Found: {{ courses.length }}</p>
</div>
}
@else if (courses.length === 50) {
<div class="alert alert-info">
<p>Our catalog is currently at maximum capacity (50 courses).</p>
</div>
}
@else {
<div class="empty-state">
<p>No courses are currently scheduled. Please check back later.</p>
</div>
}

Why use the new @if syntax?

  1. Readability: It is much easier to follow than nested *ngIf with else templates.
  2. Performance: It has less overhead than the directive-based approach.
  3. Type Narrowing: It works seamlessly with TypeScript's type-checking within the template.


FeatureLegacy Way (Directive)Modern Way (Control Flow)
Syntax*ngIf="condition; else other"@if (condition) { ... }
TemplatesRequires <ng-template>Simple curly braces {}
Generationng g interface nameSame (Interfaces remain essential)
Share this lesson: