1

I have this inside my code:

 <div *ngIf="(listCount$| async) > 0 ">

but it won't pass the pipeline because it says

Object is possibly 'null' or 'undefined'.

in ts file:

readonly listCount$ = new BehaviorSubject<number | undefined>(undefined);

any help, can i do this in one line?

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • Do you represent some specific state of application with undefined? Otherwise you could just initialise it with 0. – Lukasz Gawrys Dec 31 '21 at 13:12
  • i tried but then i made huge mess and a lot of errors inside other parts of app –  Dec 31 '21 at 13:14
  • Without changing anything else the only solution would be probably to add second condition ```!!(listCount$| async) && (listCount$| async) > 0``` but this adds second subscription as well. – Lukasz Gawrys Dec 31 '21 at 13:25
  • Initialize the subject with a number that satisfies the `*ngIf` expression instead of `undefined`? – The Head Rush Dec 31 '21 at 13:32

2 Answers2

0

It's an async operation that might result in an undefined value that's why you are getting the error. Provide a default value in case of undefined in your template condition.

<div *ngIf="((listCount$| async) ?? 0) > 0 ">

OR set the strictNullChecks to false in your tsconfig.json file.

"strictNullChecks": false

Demo:- https://stackblitz.com/edit/angular-ivy-kheete?file=src%2Fapp%2Fapp.component.html

Vimal Patel
  • 2,785
  • 2
  • 24
  • 38
0

You can use the as syntax for a clean syntax which will allow you to use the listCount as a variable. this variable will evaluate as a condition for a truty/falsy argument so (0, undefined, null, '', NaN) will evaluate as false.

<div *ngIf="(listCount$ | async) as listCount;">hello</div>
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • and where is the condition that listCount needs to be bigger then 0? –  Dec 31 '21 at 13:59