Search code examples
angularasynchronousangular6ngforangular-ngfor

Display Table Rows Using Async in Angular


I need to display the result of the JSON response in a table. I already figure it out using this below

<tr *ngFor="let result of results$ | async">
    <td>{{result.max_temp}}</td>
</tr>

But i wanna do something like this below and its not working. Can anyone help me out on how to fix this?

<tr *ngFor="let result of (results$ | async)?.max_temp">
    <td>{{result}}</td>
</tr>

Solution

  • I have these two solution which I can suggest. You can use any of them.

    Solution 1:

    <ng-container *ngIf="results$ | async as resolvedResult">
      <tr *ngFor="let result of resolvedResult.max_temp">
        <td>{{result}}</td>
      </tr>
    </ng-container>
    

    Solution 2:

    <ng-container
        *ngTemplateOutlet="asyncTemplate;context:{resolvedResult: results$ | async}">
    </ng-container>
    
    <ng-template #asyncTemplate let-resolvedResult="resolvedResult">
      <tr *ngFor="let result of resolvedResult.max_temp">
        <td>{{result}}</td>
      </tr>
    </ng-template>
    

    Please note, from the Angular docs:

    The Angular ng-container is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.