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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With