👀 Clean, Simple Conditionals in Angular with @if and @else

If you’ve been using Angular for a while, you’re probably familiar with the good old *ngIf + ng-template combo. It worked, but let’s be honest — it wasn’t exactly elegant.

<div *ngIf="isLoggedIn; else guestBlock">
Welcome back, user! 🎉
</div>

<ng-template #guestBlock>
Please log in to continue. 🔒
</ng-template>

Looks familiar? Now with Angular 19, there’s a much better way to handle conditionals. Say hello to @if and @else.


🤔 Why Change the Syntax?

Angular’s evolving — and in a good way. The new @if block syntax:

  • Makes templates easier to read
  • Cleans up boilerplate
  • Feels more like writing actual code
  • Aligns with modern frameworks (like React or Svelte)

🆚 Before vs After

Here’s a quick comparison.

Old way:

<div *ngIf="user?.name; else noUser">
Hello, {{ user.name }}!
</div>

<ng-template #noUser>
Hello, guest!
</ng-template>

New Angular 19 way:

@if (user?.name) {
<p>Hello, {{ user.name }}!</p>
} @else {
<p>Hello, guest!</p>
}

So much cleaner, right?


🧩 Nesting Made Easy

You can also nest logic naturally:

@if (user) {
@if (user.isAdmin) {
<p>Welcome, Admin!</p>
} @else {
<p>Welcome, User!</p>
}
} @else {
<p>Please sign in.</p>
}

No more jumping between ng-template tags or keeping track of reference names. Just plain, readable logic.


⚙️ How to Enable It

To use this new syntax, just make sure:

  • You’re using Angular 19+
  • Your component is standalone
  • You import CommonModule
@Component({
standalone: true,
selector: 'app-my-component',
templateUrl: './my-component.html',
imports: [CommonModule],
})
export class MyComponent {}

That’s it — no extra configuration needed.


🧠 Final Thoughts

This new control flow syntax is one of the nicest upgrades Angular has seen in a while. If you’re building something new or refactoring old code, using @if instead of *ngIf will make your templates more readable and maintainable.

I’ve already started replacing my older conditional blocks, and honestly? It feels great.


✅ TL;DR

  • @if and @else replace *ngIf and ng-template
  • Syntax is cleaner and easier to follow
  • You must be using Angular 19+ and standalone components
  • Give it a try on your next component!

Leave a Comment

Your email address will not be published. Required fields are marked *