2

I have some block of html in Angular that I would like fill out with some nested values of an observable, such as:

  <div class="container" *ngIf="(myObservable$ | async)  as myObservable">
    <span>{{ myObservable.middleNest.value1 }}</span>
    <span>{{ myObservable.middleNest.value2 }}</span>
  </div>

Is there a way to define a variable in the container tags so that I am able to fetch the nested values via middleNest.value1 and middleNest.value2 (ensuring the path to middle nest is fully non-null)? It doesn't seem right to have to write the whole path to middle nest in the spans, given that in some cases the values could be deeply nested.

Jon
  • 277
  • 2
  • 12

2 Answers2

2

You could use RxJS pluck operator in the controller to return only a specific property from the observable response

Controller

export SomeComponent implements OnInit {
  myObservable$: Observable<any>;

  ngOnInit() {
    this.myObservable$ = this.someService.getData().pipe(
      pluck('middleNest')
    );
  }
}

Now you have the middleNest object in the async emission.

<div class="container" *ngIf="(myObservable$ | async) as middleNest">
  <span>{{ middleNest?.value1 }}</span>
  <span>{{ middleNest?.value2 }}</span>
</div>

Also like @uiTeam324 showed, you could use safe navigation operator ?. to avoid potential undefined errors.

ruth
  • 29,535
  • 4
  • 30
  • 57
1

You can use safeOperator(?). It will check for undefined internally

<div class="container" *ngIf="(myObservable$ | async)  as myObservable">
  <span>{{ myObservable?.middleNest?.value1 }}</span>
  <span>{{ myObservable?.middleNest?.value2 }}</span>
</div>
uiTeam324
  • 1,215
  • 15
  • 34