20

I am trying to use the Hidden property in Angular2 and when I include a style that alters the display of the DIV, the hidden property is ignored.

When the code below is run, both divs are displayed. When I remove the class .displayInline the first DIV is hidden and the second is displayed (as expected).

Can I use Hidden and the display CSS together?

import {ComponentAnnotation as Component, ViewAnnotation as View, bootstrap, NgIf} from 'angular2/angular2';

@Component({
    selector: 'hello'
})
@View({
    template: `<style>.displayInline{ display:inline }</style><span *ng-if="name">Hello, {{name}}!</span>
    <div>
                <div [hidden]="hideDiv1()" class="displayInline">should be hidden.</div>
                <div [hidden]="hideDiv2()" class="displayInline">should be displayed.</div>
    </div>`,
    directives: [NgIf]
})
export class Hello {
    name: string = 'World';
    constructor() {
        setTimeout(() => {
          this.name = 'NEW World'
        }, 2000);
    }

    hideDiv1(){
        return true;
    }   

    hideDiv2(){
        return false;
    }
}

bootstrap(Hello);

Repository:https://github.com/albi000/ng2-play

Gaurav Mukherjee
  • 6,205
  • 2
  • 23
  • 33
Albi
  • 303
  • 1
  • 2
  • 5

3 Answers3

33

I faced similar problem with btn class of bootstrap

<button [hidden]="!visible" class="btn btn-primary">Click</button>

I solved this by adding

[hidden] {
  display: none;
}

at the end of css stylesheet I use globally. This is solved the problem for now.

Gaurav Mukherjee
  • 6,205
  • 2
  • 23
  • 33
17

Note: <span>'s default to "display: inline", you may want to use them instead.

Currently classes override [hidden]. I agree, this isn't as effective as ng-hide/ng-show and I hope it is fixed in future versions of angular2. It is currently an open on issue on the Angular2 repo.

You can overcome the problem by simply wrapping your [hidden] element with the class.

<span class="someClass">
  <span [hidden]="hideDiv1()">should be hidden.</span>
</span>
shmck
  • 5,129
  • 4
  • 17
  • 29
  • The referenced issue has been closed, and I suspect it has been rolled up with some `aria-hidden` work. I have asked for clarification. See [differences](https://www.paciellogroup.com/blog/2012/05/html5-accessibility-chops-hidden-and-aria-hidden/). – Stajs Mar 10 '16 at 22:04
  • It works but If we write `span` tag inside a `tr` of a `table` it breaks the table row. How can I fix this? – Eesa May 05 '16 at 15:52
12

You can use style.display instead of hidden if you need more fine-grained control over visibility.

<div [style.display]="active?'inherit':'none'"></div>
justind
  • 1,259
  • 13
  • 16
  • This one is great to efficiently replace *ngIf="active" when the div have a nested component which need to be bootstraped – Weber Antoine Feb 09 '16 at 16:30