gpt4 book ai didi

Angular 2 : is there a way to know when a component is hidden?

转载 作者:太空狗 更新时间:2023-10-29 17:30:17 26 4
gpt4 key购买 nike

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的使用可以在这个post找到.

检查子组件是否被隐藏

您可以在 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<boolean>();
active: boolean;

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

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

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

关于 Angular 2 : is there a way to know when a component is hidden?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com