簡體   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