簡體   English   中英

如何在Angular 6中沒有* ngIf的情況下將異步管道的結果分配給變量

[英]How to assign result of async pipe to variable without *ngIf in Angular 6

是否可以在沒有 *ngIf 的情況下將 (areShipsExpanded$ | async) 分配給變量? 因為如果這是標志true / false當我有: *ngIf="(areShipsExpanded$ | async) as flag"那么按鈕不會在 false 的情況下顯示。

我想要這樣的東西:

<button *let="(areShipsExpanded$ | async) as flag"
   (click)="expandAllShips(flag)">{{(flag ? "Collapse" : "Expand"}}
</button>

你可以使用ng-templateng-container

<ng-template #myTempl let-flag="areShipsExpand">
      <button
   (click)="expandAllShips(flag)">{{flag ? "Collapse" : "Expand"}}
  </button>
</ng-template>

<ng-container *ngTemplateOutlet="myTempl; context:{areShipsExpand: areShipsExpanded$ | async}"></ng-container>

演示

在這里參加聚會有點晚,但我從這篇中等文章中找到了一個很好的例子來說明如何做到這一點

你仍然使用*ngIf但你確保它總是通過傳入一個新對象作為屬性來評估你的可觀察值。

<div *ngIf="{value1: myObs$ | async} as valuesObj">
    {{ valuesObject.value1 }}
</div>

IMO 這仍然有點hacky,但比其他答案或創建您自己的*ngLet指令要少得多。

正如文章中提到的,這也是將多個對象屬性中的多個可觀察值組合在一起的好方法,因此您不必有多個async語句或嵌套的<ng-container>元素。

使用來自@ngrx/component*ngrxLet指令

<ng-container *ngrxLet="observableNumber$ as n">
   <app-number [number]="n">
   </app-number>
</ng-container>

包含ngrxLet指令的元素的可見性不受可觀察表達式的值的影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM