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

1

15

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>
}
Gehrke answered 23/11, 2023 at 2:42 Comment(1)
Sure, in your usage it can, but I'm not sure if @if can completely replace <ng-container> -- see <ng-container> usage in this answer about reactive formsSkin
L
9

Update:

Angular v18 is now available and control flow is stable, So the answer is yes. Let's use and enjoy this new feature!

Old answer (angular v17):

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
} 
Loran answered 16/2 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.