繁体   English   中英

*ngIf 中的 Angular 异步 pipe - 处理 0 值

[英]Angular async pipe in *ngIf - handle 0 value

我有以下 html 片段:

<div *ngIf="calculatedValue$ | async as calculatedValue">
  {{calculatedValue}}
</div>

但是如果计算的Value$ 发出的值为0(类型=数字),则该div 将不会显示在DOM 中。

显示它的正确方法是什么? 可能是以非 null 检查添加到 *ngIf 的方式。

正如你已经建议的那样; 它的类型需要是数字。

typeof (calculatedValue$ | async) === 'number'

或者根本不是 null

(calculatedValue$ | async) !== null

而不是 *ngIf,只需使用 *ngLet。 在 web 上有多种实现,例如在https://github.com/ngrx/component-builds中。 老实说,我不明白为什么这仍然不是 angular 内核的一部分。

如何在评论中提及@joosep 部分,您可以将值分配给 object,例如此代码显示进度条,即使其值为 0

组件.ts

progress$ = new BehaviorSubject<number>(0);

组件.html

<ng-container *ngIf="{ value: progress$ | async } as progress">
    <app-progressBar
       [value]="progress.value"
    ></app-progressBar>
</ng-container>

这是预期的行为。 以下是 javascript 当前转换为 false 的所有值:

if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (``)

https://stackblitz.com/edit/async-pipe-jghgvc?file=app%2Fasync-pipe%2Fasync-pipe.component.html

解决此问题的最简单方法是将发出的值从 observable 转换为 object 上的属性。 您可以在组件 class 文件中执行此操作,或直接在 HTML 中执行此操作。 我将直接在 HTML 中执行此操作。 看起来是这样的:

<ng-container *ngIf="{ observableValue: promise | async } as calculatedValue">
    <div>{{ calculatedValue.observableValue }}</div>
</ng-container>

我们在这里所做的是使用异步 pipe 订阅 observable,并将值放入 object 的 observableValue 属性中。 注意 *ngIf 结构指令中的大括号。 然后我们使用 as 语法,它重命名变量以在模板中使用。 在双大括号内,通过访问数据 object 的 observableValue 属性,结果为 output。 ng-container 元素上的 *ngIf 指令现在将始终评估为 true,因为我们已经创建了 object。 因此,无论从 observable 发出什么值,我们都会将其 output 到屏幕上。

此处正在跟踪此问题: https://github.com/angular/angular/issues/15280

使用您的用例实现的解决方法之一如下所示:

 <div  *ngIf="{ calculatedValue: calculatedValue$ | async } as context">
    {{ context.calculatedValue }}
 </div>

另一种最有可能的方法,目前唯一的方法是在您的.ts组件中订阅它,然后使用该属性检查 null 值。

暂无
暂无

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

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