简体   繁体   English

如何在ngIF条件下检查object是null还是在angular中未定义

[英]how to check if object is null or undefined in angular in ngIF condition

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:在 ts 文件中:

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

any help, can i do this in one line?任何帮助,我可以在一行中做到这一点吗?

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.或者在tsconfig.json文件strictNullChecks设置为 false。

"strictNullChecks": false

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

You can use the as syntax for a clean syntax which will allow you to use the listCount as a variable.您可以将as语法用于干净的语法,这将允许您将 listCount 用作变量。 this variable will evaluate as a condition for a truty/falsy argument so (0, undefined, null, '', NaN) will evaluate as false.此变量将评估为 truty/falsy 参数的条件,因此 (0, undefined, null, '', NaN) 将评估为 false。

<div *ngIf="(listCount$ | async) as listCount;">hello</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM