Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Show or hide elements without effecting element spacing

Tags:

html

css

angular

I have a row of divs that contain information such as the brand name and image. If a brand has a name I would like to display it else leave it blank. The problem is not all products have brand name.I want to keep the spacing the consistent regardless of the fact if there is a name or not.

I already tried ngIf and the hidden directive but both do not have the desired result.

<div  *ngFor="let product of products">
    <h5 class="product-brandname" [hidden]="!product.brandname">{{product.brandname}}</h5>
   <img/>
   etc...
</div>

https://www.dropbox.com/s/ucs51qugchvfxso/Screen%20Shot%202019-01-28%20at%202.03.48%20PM.png?dl=0

like image 681
user7659932 Avatar asked Oct 21 '25 05:10

user7659932


1 Answers

To make sure that the h5 element does not collapse, set an unbreakable space as the defaut value:

<h5 class="product-brandname">{{ product.brandname || "&nbsp;" }}</h5>

If you really want to hide empty h5 elements that still occupy the same space, set their style visibility attribute to hidden. In that case, the default text can be any non-empty string:

<h5 class="product-brandname" [style.visibility]="product.brandname ? 'visible' : 'hidden'">
  {{ product.brandname || "Any text" }}
</h5>

See this stackblitz for a demo.

like image 60
ConnorsFan Avatar answered Oct 23 '25 21:10

ConnorsFan