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.
In the generated course.ts file, we define our structure. Using interfaces prevents runtime errors by catching type mismatches during development:
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.
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
Why use the new @if syntax?
- Readability: It is much easier to follow than nested
*ngIfwithelsetemplates. - Performance: It has less overhead than the directive-based approach.
- Type Narrowing: It works seamlessly with TypeScript's type-checking within the template.
| Feature | Legacy Way (Directive) | Modern Way (Control Flow) |
| Syntax | *ngIf="condition; else other" | @if (condition) { ... } |
| Templates | Requires <ng-template> | Simple curly braces {} |
| Generation | ng g interface name | Same (Interfaces remain essential) |