3

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.

2
  • 1
    You can try just (profiles$ | async)?.length > 0. I guess in the second example the compiler can't know that the value has to exist because of (profiles$ | async). Commented Dec 21, 2020 at 23:01
  • Yes, that works! Thank you :) Commented Dec 21, 2020 at 23:20

1 Answer 1

7

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>
Sign up to request clarification or add additional context in comments.

Comments

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.