Say goodbye to Angular directives like *ngIf
, *ngFor
, and *ngSwitch
. Now with the latest update to Angular, you can replace these directives with Angular’s new built-in control flow keywords. These keywords help streamline template management by offering a more concise and intuitive way to handle conditional rendering and loops. Let’s explore what this new built-in control flow is all about.
Meet the New Control Flow Crew 🧑✈️
@if
: The new replacement of*ngIf
. It allows you to conditionally render template sections based on a boolean expression.@for
: Adiós*ngFor
,@for
is now used to iterate over arrays and collections, therefore dynamically generating template elements for each item.@switch
: Inspired from*ngSwitch
,@switch
evaluates an expression and displays content based on the matched case, offering a cleaner alternative.
This really helps in boosting readability as the new syntax aligns with other programming languages making your code easier to maintain. Let’s see the magic of these keywords in action with some code examples:
Conquering Conditionals with @if
Suppose you want to display a welcome message only when a user is logged in. Here’s how @if
simplifies things:
The above code snippet only renders the welcome message if the isLoggedIn
property in your component is true
. Otherwise, it renders a sign-in message.
Looping Like a Pro with @for
Say you have an array of items and want to display each one in a list. @for
comes to the rescue:
This code iterates over the items
array, rendering a list of items. You can also include an @empty
block immediately after the @for
block content. The content of the @empty
block is only displayed when there are no items in the array:
Mastering Multi-Branching with @switch
Suppose you need to display different content based on a user’s role. @switch
handles it with ease:
This code snippet checks the userRole
property and displays the corresponding content. The @default
case as an else clause.
Embrace the Power of Built-in Control Flow
The built-in control flow keywords offer a significant upgrade to your Angular template experience. With their improved readability and type safety, these keywords can undoubtedly streamline your development workflow.
So, the next time when you’re building your Angular application, consider these new features to write cleaner, more maintainable, and future-proof code. Also, check out my other blog where I discuss what’s new in Angular 18. Happy coding!
Hey this is quite a good read. We recently looked on X and I saw your pinned tweet.