Generaldeep
Generaldeep

Reputation: 445

Angular template, remove div and white space (div is removed, but not white space)

Edit: After more thoughts, i am removing the unnecessary element within the TS file and making my template file do less work.

I've looked at a few stack o/f threads about removing a div and the white space that it takes. Such as this one

The div is hidden, however the white space is still there on my template.

code

<div *ngIf="array[i] !== null; else hideDivAndRemoveWhiteSpace">
  //business logic
</div>
<ng-template #hideDivAndRemoveWhiteSpace>
  //this template should be hidden
  <div class="hide-div"></div>
</ng-template>

css

.hide-div {
  display: none;
}

Upvotes: 0

Views: 7288

Answers (3)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24414

you may add this option to the component decorator preserveWhitespaces: false

this will remove the elemnt from the dom

<div *ngIf="false" >
..
</div>

false mean any falsy value

add class base on condtions

style.css

.d-none {
 display:none
}

template

<div [ngClass]="{'d-none': true}">
...
</div>

or you can use ng-container so you don't need to wrap you business logic with any div elemnt

<ng-container *ngIf="condition">
 //business logic
</ng-container>

if conditiontrue the container business logic elements will be visible if it false nothing will render to the dom

Upvotes: 0

Nadhir Falta
Nadhir Falta

Reputation: 5257

you can use <ng-container> </ng-container>

See Angular's documentation about ng-container how Angular doesn't add it to the DOM

https://angular.io/guide/structural-directives#ng-container-to-the-rescue

Also, see this answer:

<ng-container> vs <template>

Upvotes: 1

David ROSEY
David ROSEY

Reputation: 1805

Which whitespace are tlaking about ?

In your code, why wouldn't you just do:

<div *ngIf="array['data']">
    //business logic
</div>

without the "ele" and the "ng-template"

Upvotes: 0

Related Questions