【发布时间】:2020-04-30 06:29:57
【问题描述】:
我只想在用户看到加载数据的特定组件时才加载数据。所以在组件可见之前不要加载。
我有这个模板:
<button (click)="showMyCompontente()">Click me</button>
<app-other-component *ngIf="show"></app-other-component>
使用此 TypeScript 代码:
export class MyComponent implements OnInit {
show = false;
ngOnInit() {
}
showMyCompontente() {
this.show = !this.show;
}
}
重点就在这里:
@Component({
selector: 'app-other-component',
})
export class OtherComponent implements OnInit {
ngOnInit() {
this.load();
}
load() {
// needs to load datas only if the user see the component
}
}
只有当组件对用户可见时,如何在OtherComponent 中启动this.load()?如果用户隐藏组件并再次显示它,我想再次重新加载数据。
我需要组件内部的解决方案来检测自身是否变得可见或消失。那是因为我有很多组件,互相称呼的方式多种多样。
只有在用户显示组件时才会触发哪个 Angular 生命周期钩子?
【问题讨论】:
-
你试过
ngAfterViewInit()吗?否则,您必须提供更多代码来阐明如何显示和隐藏组件。 -
你一定在寻找 AfterViewInit
-
@Kokodoko 是的,但是在渲染父组件时它也会运行。
标签: javascript angular typescript angular-lifecycle-hooks