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?
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.
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.
Async pipe is an example of an Impure pipe.
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.
This might work
<img [src]="(obs$ | async) ? (obs$ | async)[0] : null">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With