Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Async pipe for array index

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?

like image 354
Dynalon Avatar asked Aug 09 '16 08:08

Dynalon


People also ask

Can async pipe be used with NgFor?

Use the async pipe with ngIf We above example uses the async pipe with interpolation. We can also use it with the ngIf or ngFor etc.

What is async pipe used for?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Is async pipe impure?

Async pipe is an example of an Impure pipe.

What type of data works with async pipe in angular?

We can use the async pipe in Angular application by including the CommonModule which exports all the basic Angular directives and pipes, such as NgIf, NgForOf, DecimalPipe, and so on.


1 Answers

This might work

<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
like image 122
Günter Zöchbauer Avatar answered Oct 13 '22 08:10

Günter Zöchbauer