1

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. In my scenario I need div element to be always present in DOM. So I was trying <div [hidden]='!condition | async as data'> I found that async doesn't work with [hidden]

Viswa
  • 745
  • 10
  • 30
Godric Gryffindor
  • 653
  • 1
  • 7
  • 10

2 Answers2

0

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

<!--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>
Etheraex
  • 508
  • 6
  • 17
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • i tried this and i am getting unexpected token 'as' and unexpected token obj – Godric Gryffindor Jun 04 '21 at 06:40
  • And one more thing i dont want *ngIf as that removes html element from DOM, I want the html element to be present in DOM always so instead of *ngIf I am using [hidden] – Godric Gryffindor Jun 04 '21 at 06:42
  • @GodricGryffindor, I just make a stackblitz https://stackblitz.com/edit/angular-ivy-9vc3ey?file=src%2Fapp%2Fapp.component.html -condition is an observable -I create it using rxjs `of` and work for me. About hidden use `
    `, really I like more `
    `
    – Eliseo Jun 04 '21 at 07:28
0

You can add a class to your element (or style), and with this set the visibility to hidden:

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:

    <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.

Lars Rødal
  • 809
  • 1
  • 9
  • 26