Markus
Markus

Reputation: 2062

Angular check if observable is null in template

I have an observable defined in my angular component like this.

profiles$!: Observable<Profile[] | undefined>;`

I try to check the length of this array in my template like this.

<div *ngIf="(profiles$ | async).length > 0"></div>

With this construct I get the error message Object is possibly 'null' or 'undefined'. from the typescript compiler which is totally fine. So add a null check to my if condition.

<div *ngIf="(profiles$ | async) && (profiles$ | async).length > 0"></div>

I'm still getting the same error that the object is possible null. I guess the compiler dose not recognise the null check. My question is how to do the null check to avoid the error from the typescript compiler.

Upvotes: 3

Views: 4505

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

the problem will happen in case the observable return a null

<div *ngIf="(profiles$ | async).length > 0"></div>

a quick way solve to this problem is to use the safe navigation operator ?

<div *ngIf="(profiles$ | async)?.length > 0"></div>

or you can use ng-container with ngIf in case you want to apply extra check of the return value of the observable

<ng-container *ngIf="(profiles$ | async) as result">
  <div *ngIf="result.length > 0"></div>
</ng-container>

Upvotes: 7

Related Questions