Search code examples
angularangular-directive

Hide HTML Element but Keep It's Spacing In Angular


I'm working in an Angular 11 Project.

I know there's the ngIf directive, which will only show the html element if set to true, but doesn't preserve spacing.

In the old AngularJS, there was ng-show and ng-hide. These properties would show/hide an element, but keep its spacing (effectively setting the css to visibility to hidden). But Angular no longer has those properties. Instead they recommend binding to the hidden property (https://angular.io/guide/ajs-quick-reference#ng-show).
However, this doesn't preserve the spacing (which is strange IMO).
Does Angular have a directive that hides the element while also preserving its spacing?

I can add a conditional class, where the class has a visibility of hidden, but I trying to confirm if Angular has a directive/property for this.

I wiped up a demo here: https://stackblitz.com/edit/hide-element-angular?file=src/app/autocomplete-auto-active-first-option-example.html
This shows the hidden and ngIf do not perserve spacing, while the conditional class will.


Solution

  • The issue is a CSS issue, namely the bootstrap/CSS framework [hidden] definition has display: none defined. The hide class rightfully so has visibility: hidden;.

    If we add:

    .inner-div[hidden] {
      visibility: hidden;
      display: block !important;
    }
    

    to styles.scss, it will fix the issue.

    Having .inner-div as part of the definition might not be good but it is tough because the definition from the CSS framework is:

    [hidden] {
      display: none !important;
    }
    

    and it is difficult to override that !important.

    Picture of styling in Chrome Dev Tools