8

Angular2: is there a way to know when a component which happens to be a child of this component which gets hidden, loses or gains visibility?

template: `
   <div [hidden]="!active" class="pane">
       <ng-content></ng-content>
    </div>
    `

regards

Sean

born2net
  • 24,129
  • 22
  • 65
  • 104

1 Answers1

21

Check if the component is hidden from within the component itself

import {Component, OnInit, ElementRef} from '@angular/core';

@Component({
    selector: 'child-component',
    template: `<div>Hello</div>`
})

export class ChildComponent implements OnInit {
    constructor(private elementRef: ElementRef) { }

    ngOnInit() {
        const element = this.elementRef.nativeElement;

        if(element.offsetParent === null) {
            // element is not visible
        }
    }
}

The use of offsetParent can be found at this post.

Check if a child component is hidden

You could emit an event when active changes.

import {Component, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'my-component',
    template: `
    <div [hidden]="!active" class="pane">
       <ng-content></ng-content>
    </div>
    <button (click)="toggleActive()">Click</button>`
})

export class MyComponent {
    @Output() onActive = new EventEmitter<boolean>();
    active: boolean;

    toggleActive() {
        if(this.active) {
            this.active = false;
        } else {
            this.active = true;
        }

        this.onActive.emit(this.active);
    }
}

Then just subscribe to that event in your parent component.

Community
  • 1
  • 1
Barry Tormey
  • 2,966
  • 4
  • 35
  • 55
  • tx I know that, but the component that needs to act upon the show/hide should not be aware of its parent component... self contained – born2net Jun 15 '16 at 19:46
  • I'm not sure I fully understand you then. I thought what you were asking is how to notify a parent that a child has been hidden. In the case I provided, the child (shown) is not aware of the parent, it is simply emitting an event that anyone can subscribe to, this does not tightly couple the two components. – Barry Tormey Jun 15 '16 at 19:53
  • Hi Barry, yes you have, but in my case, the child component is self contained and to achieve good encapsulation, my child should not be "parent aware" so I'd like the child to just be able to "sense" when it is being CSS display show / hidden... sorry I wasn't clear, regards – born2net Jun 15 '16 at 20:10
  • @born2net I updated my answer to reflect what I think you're looking for. – Barry Tormey Jun 15 '16 at 20:40
  • `offsetParent` returns null even do I have `[hidden]` set to hide the element. If I use the console, I can see `hidden: true` but I can't access it to verify the value. It shouldn't be this hard to verify this. – acarlstein Mar 09 '23 at 21:49