Angular V17: Prospects of @if vs. *ngIf – Will *ngIf be Deprecated in the Future?

7k views Asked by At

In the new version of Angular V17, the @if directive can be used as a replacement for ng-container, which is fantastic. However, sometimes *ngIf is more concise, such as when determining whether to display a button:

<button *ngIf="loaded">OK</button>

Therefore, I would like to ask, what is the outlook for *ngIf? Will Angular completely abandon *ngIf in some future version?

Should we replace all instances of *ngIf with @if now, even though the above code may not look as elegant as before?

@if(loaded){ 
    <button>OK</button>
}
1

There are 1 answers

1
Alireza Ahmadi On

The control_flow concept is labeled as developer preview in Angular website which means:

They are fully functional and polished, but that they are not ready to stabilize under their normal deprecation policy.

Also they have an efficient way of migrating from old template syntax to a new one introduced in Angular v17

Now let's get back to your questions:

Should we replace all instances of *ngIf with @if?

I recommend waiting a few months for the Angular team to officially designate this feature as stable. Once confirmed, you can be sure that no rework is necessary, especially if you are working on a sizable project.

Will Angular completely abandon *ngIf in some future version?

While the Angular team hasn't officially stabilized the control_flow yet, the definitive answer remains uncertain. However, personally, I would say No. Even if they label the old syntax as deprecated, it should still be usable, given the prevalence of applications employing this format. Furthermore, there's no need to be concerned about migrating from the old syntax to the new one, as you can easily accomplish it by running the following command.

ng g @angular/core:control-flow

Side notes: By using @If you can get rid of using ng-template which is really great feature. look at this example:

<div *ngIf="loggedIn; else anonymousUser">
  The user is logged in
</div>
<ng-template #anonymousUser>
  The user is not logged in
</ng-template>

With the built-in if statement, this condition will look like:

@if (loggedIn) {
  The user is logged in
} @else {
  The user is not logged in
}