简体   繁体   English

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

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

I have我有

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

which is removing the div element from DOM.这是从 DOM 中删除 div 元素。 In my scenario I need div element to be always present in DOM.在我的场景中,我需要 div 元素始终存在于 DOM 中。 So I was trying <div [hidden]='!condition | async as data'>所以我在尝试<div [hidden]='!condition | async as data'> <div [hidden]='!condition | async as data'> I found that async doesn't work with [hidden] <div [hidden]='!condition | async as data'>我发现 async 不适用于 [hidden]

when you has an "async" and you need "repeat", a tipical way is create "on fly" an object in a ng-container and ask about the object当您有“异步”并且需要“重复”时,一种典型的方法是在 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>

You can add a class to your element (or style), and with this set the visibility to hidden:您可以将 class 添加到您的元素(或样式),并将可见性设置为隐藏:

Setting style directly:直接设置样式:

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

Adding a class to set CSS through that:添加一个 class 来设置 CSS 通过它:

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

(Have not tested using 'as' inside these bindings, but assume that will work - using the data/pipe itself I have tested before. (尚未在这些绑定中使用 'as' 进行测试,但假设这会起作用 - 使用我之前测试过的数据/管道本身。

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

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