angularif-statementangular-ng-ifangular17

Angular 17 - In @if syntax, how to store returned value from a function in a variable and use it in the same @if block


In my case, I have following block of code that I can store the info value in the *ngIf expression block and use in the template, how to do the same with newly introduced @if syntax in Angular 17?

I couldn't find any samples/docs that can do the same using @if syntax.

<div *ngIf="getMatchingImage() as info">
  <img class="empty-cart-img" [src]="info.imageUrl" width="70%" decoding="async" loading="lazy" alt="Empty List">
  <figcaption>
    <ng-content></ng-content>
  </figcaption>
</div>

Solution

  • For the @if block, the syntax will be:

    @if (<value>; as <variable>)
    
    @if (getMatchingImage(); as info) {
      <img
        class="empty-cart-img"
        [src]="info.imageUrl"
        width="70%"
        decoding="async"
        loading="lazy"
        alt="Empty List"
      />
      <figcaption>
        <ng-content></ng-content>
      </figcaption>
    }
    

    Demo @ StackBlitz

    Reference: Angular - @if