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

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


UPDATED ANSWER

I think I understand what you're looking for now. You want the component itself to be aware as to whether or not it is hidden. I think you might be able to do something like this, however, I have not tested it...

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.

ORIGINAL ANSWER

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<bool>();
    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.

链接地址: http://www.djcxy.com/p/83572.html

上一篇: 高效地获取元素的可见区域坐标

下一篇: angular2:有没有办法知道组件何时被隐藏?