-1

We have a clear solution from here Angular Template: How to bind RXJS Observable and read its properties?

  <ng-container *ngIf="( game$ | async ) as game">
    <h3>{{ game.name }}</h3>
    <h3>{{ game.description }}</h3>
  </ng-container>

However, in case if we need a 0th player of a 0th command from the example above as a property from a deeper nested object, should we do it this way

  <ng-container *ngIf="( game$ | async )?.command?.[0]?.players?.[0] as player">
    <h3>{{ player.name }}</h3>
    <h3>{{ player.description }}</h3>
  </ng-container>

or there is a better way?

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

1 Answers1

2

You can use some so "bizarro" as

<ng-container *ngIf="( game$ | async ) as game">
    <h3>{{ game.name }}</h3>
    ------------------------
    <h3>{{ game.command?.[0]?.players?.[0].name }}</h3>
    <h3>{{ game.command?.[0]?.players?.[0].description }}</h3>
</ng-container>

Or create a temporaly variable using *ngIf

<ng-container *ngIf="( game$ | async ) as game">
    <h3>{{ game.name }}</h3>
    ------------------------
    <ng-container *ngIf="game.command?.[0]?.players.[0] 
                         || {name:'',description:''} as player">
    <h3>{{ player.name }}</h3>
    <h3>{{ player.description }}</h3>
</ng-container>

Or create a new Observable based in game$ using map

players$=this.game$.pipe(
   map(x=>x.command?.[0]?.players?.[0])
))
Eliseo
  • 50,109
  • 4
  • 29
  • 67