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

Angular2:有没有办法知道什么时候碰巧是这个组件的一个子组件被隐藏,丢失或获取可见性?

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

问候

肖恩


更新的答案

我想我明白你现在在找什么。 您希望组件本身知道它是否隐藏。 我认为你也许可以做这样的事情,但是,我没有测试过......

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
        }
    }
}

在这篇文章中可以找到offsetParent的使用。

原始答案

active更改时可以发出一个事件。

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);
    }
}

然后只需在您的父组件中订阅该事件。

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

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

下一篇: create if conditional based on css properties