Search code examples
angularif-statementangular17

in @if syntax of angular 17 : how to store returned value from a function in a variable and use it in the very same @if block


In my case ,

I have following block of code, In which, 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