簡體   English   中英

在 Angular 2+ 中將“*ngIf= 'condition | async as data' 更改為 [hidden]”

[英]Changing "*ngIf= 'condition | async as data' to [hidden]" in Angular 2+

我有

 <div *ngIf='condition | async as data'>
    <div *ngIf='data.length > 0'>some html to render ...
    </div>
 </div>

這是從 DOM 中刪除 div 元素。 在我的場景中,我需要 div 元素始終存在於 DOM 中。 所以我在嘗試<div [hidden]='!condition | async as data'> <div [hidden]='!condition | async as data'>我發現 async 不適用於 [hidden]

當您有“異步”並且需要“重復”時,一種典型的方法是在 ng 容器中“即時”創建 object 並詢問 object

<!--see that the property is always true-->
<ng-container *ngIf="{data:condition|async} as obj">
  <!--see that you ask about obj.data-->
  <!--I use an unique *ngIf-->
  <div *ngIf="obj.data && obj.data.length">
           ..put your code...
           ..if data is an array you can iterate..
           ..eg.
      <div *ngFor="let item of obj.data">
           {{item.id}}
      </div>
  </div>
</ng-container>

您可以將 class 添加到您的元素(或樣式),並將可見性設置為隱藏:

直接設置樣式:

<div [style.visibility]="((condition | async) as data) ? 'visible' : 'hidden'"><div *ngIf='data?.length'>some html to render ...</div></div>`

添加一個 class 來設置 CSS 通過它:

    <div [class.hidden]="((condition | async) as data)"><div *ngIf='data?.length'>some html to render ...</div></div>`

(尚未在這些綁定中使用 'as' 進行測試,但假設這會起作用 - 使用我之前測試過的數據/管道本身。

暫無
暫無

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

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