Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2: is there a way to know when a component is hidden?

Tags:

angular

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

like image 792
born2net Avatar asked Jun 15 '16 19:06

born2net


1 Answers

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.

like image 87
Barry Tormey Avatar answered Sep 19 '22 01:09

Barry Tormey