7

I have an observable of string Arrays const obs$: Observable<string[]> on my component as a property. While I can successfully use the async pipe on a *ngIf statement, the pipe fails when accessed via array indexer (obs$ | async)[0].

Example:

<!-- evaluates the array emmitted by obs$ for truthyness -->
<div *ngIf="obs$ | async">
    <!-- only shown if obs$ emitted an array with length > 0 -->

    <!-- but this fails with error: Cannot read property '0' of null -->
    <img [src]="(obs$ | async)[0]">
</div>

The instance of obs$ is set in the component's constructor, so obs$ shouldn't be undefined when the template is data-bound.

How to properly access the array's elements in the template?

2
  • There already has been submitted a bug report - the issue will be fixed in RC.5 Commented Aug 9, 2016 at 8:47
  • Not a duplicate per se; The solution in the duplicate answer does only apply (use ngFor) if you want to iterate over an array; there is no solution for directly accesing an array by a known index Commented Aug 9, 2016 at 9:04

2 Answers 2

5

This might work

<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
Sign up to request clarification or add additional context in comments.

2 Comments

In fact, I was almost certain it would work, but I came on these subjects to find a more elegant solution than a ternary operator. But hey, we can't always lose too much time for this kind of details so I'll use this for now.
Be careful when using this advice, there is a very subtle caveat here. Using the async pipe twice creates two subscriptions to the underlying observable, which might result in two completely different streams (which most commonly is not the case but there are edge cases). The condition (obs$ | async)[0] == (obs$ | async)[0] is NOT true in all cases. Example: const obs$ = defer(() => [new Date().getTime())].
-1

I would try the Elvis operator at this level since your data is undefined at the beginning:

<img [src]="(obs$ | async)?[0]">

4 Comments

Neither ? nor ?? (actual elvis operator) work. Additionally, I can't see why obs$ should be undefined if used in the *ngIf block
The issue will be fixed in RC.5 - see this bug report
I've upgraded to RC5 (which was release yesterday) and the problem still persists. The neither elvis operator ?. nor a single question mark can be used for array indexes, still.
The Elvis operator doesn't work when it comes to addressing a specific array index provided by an Observable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.