angulartypescriptangular17angular-observable

Angular 17 - How to use async values in object using new @if syntax


In the previous *ngIf directives we were able to chain multiple async operations to not repeat the async pipe in the template but to reuse them later as one subscription, now I want to use the same behavior using the new @if syntax provided in Angular 17, is it possible?

Old way:

<ng-container *ngIf="{
   test: test$ | async,
   anotherOne: anotherOne$ | async,
   // and so on...
} as data">
  <span *ngIf="data.test.length">Show something</span>
</ng-container

I want to replace the code above to use only @if statement

@if({
   test: test$ | async,
   anotherOne: anotherOne$ | async,
   // it doesn't work that way
} as data) {
   <!-- show something -->
}

Solution

  • You need the ; (semicolon) before as.

    @if({ test: test$ | async, anotherOne: anotherOne$ | async }; as data) { 
      <!-- show something -->
    }
    

    Reference: Angular - @if (Description)

    Demo @ StackBlitz