Search code examples
angularangular-ng-if

Angular - How to use ngIf on async value


Apologies for what might seem like a basic question.
Is there a way to only show the wrapper div if the 'album_title' value exists? Below is what I've tried so far.

    <div *ngIf="album?.album_title">
        <div> Album </div>
        <div> {{ (album | async)?.album_title }} </div>
    </div>

    <div *ngIf="album?.album_date">
        <div> Album Date</div>
        <div> {{ (album | async)?.album_date }} </div>
    </div>

    <div *ngIf="album?.album_rating">
        <div> Album Rating</div>
        <div> {{ (album | async)?.album_rating }} </div>
    </div>

Update Updated to clearly show multiple values might be present.

UPDATE: Answer based on Saravanan Nandhan response

  <div *ngIf="album | async as album">
    <div *ngIf="album.album_title">
      <div> Album Titel </div>
      <div> {{ album.album_title }} </div>
    </div>
   <div *ngIf="album.album_date">
      <div> Album Date </div>
      <div> {{ album.album_date }} </div>
    </div>
  </div>

Solution

  • Instead of waiting for each album$ | async operation to be fully available, which likely requires more conditional checking further down inside the child presentational components, we can adopt a slightly different approach:

    <div *ngIf="album$ | async as album">
      <div> Album </div>
      <div> {{ album.album_title }} </div>
    </div>
    

    Note the addition of as album at the end of the expression.

    What this will do is wait until album$ | async has evaluated, and bind the result to the value of album (non-dollar-suffixed).

    PS - You might want to change the property name on your Component Class from album to album$

    The prop$ dollar suffix is generally used to indicate something is an Observable source.