![](/img/trans.png)
[英]How to check for a value in array of strings with ngIf using async pipe?
[英]ngIf Async Pipe as value with only null check
我有一個 observable,我想在 ngIf 中創建一個變量,並且如果值為 null 則只返回 false(observable 返回一個數字)
我需要明確檢查 null,因為我的可觀察對象可以返回 0 作為觸發 else 塊的值。
我嘗試了以下
*ngIf="(observable$ | async) as obs; obs !== null; esle #elseTemplate"
*ngIf="((observable$ | async) as obs) !== null; esle #elseTemplate"
*ngIf="(observable$ | async) !== null; $implicit = obs; else #elseTemplate"
// this returns the boolean
我目前看起來不太優雅的解決方案是
*ngIf="(observable$ | async) !== null; esle #elseTemplate"
{{ observable$ | async }}
我正在使用 Angular 10。
通常,當我像這樣處理模板中的可觀察對象時,我發現創建單個 vm$ 可觀察對象要容易得多,它是從組件中的其他可觀察對象構建的,就像這樣(注意,最終 combineLatest 將支持字典,這意味着你不會有做地圖):
vm$ = combineLatest([
this.observable$,
this.observable2$
])
.pipe(
map(([observable, observable2]) => ({
observable,
observable2
}))
);
然后在您的 dom 中,您對 vm$ 執行 ngIf,您可以直接比較 observable 的 output。
<ng-container *ngIf="vm$ | async as vm">
<ng-container *ngIf="vm.observable !== null; else #elseTemplate">
</ng-container>
...
</ng-container>
編輯當 combineLatest 支持字典時,vm$ 的創建變得更簡單:
vm$ = combineLatest({
observable: this.observable$,
observable2: this.observable2$
})
我可以推薦的另一種方法是使用來自 Nils Melhorn 的 ngx observe 指令https://github.com/nilsmehlhorn/ngx-observe
使用此指令,您可以為下一步、加載甚至錯誤定義模板。 如果發出像零這樣的虛假值,也會觸發下一個模板。
*ngxObserve="observable$; let obs; before loadingTemplate; error errorTemplate"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.