组件在 Angular 8 中可见后如何 运行 运行?
How to run function after a component became visible in Angular 8?
我只想在用户看到加载数据的特定组件时加载数据。所以不要在组件可见之前加载。
我有这个模板:
<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 生命周期挂钩仅在用户显示组件时触发?
我会尝试:
- 将布尔类型的输入 属性 添加到
OtherComponent
组件。
- 将
show
的值传递给输入 属性,然后在 OtherComponent
组件内部,使用 ngOnChanges
检测输入 属性 中的任何变化并相应地调用 load()
。
我只想在用户看到加载数据的特定组件时加载数据。所以不要在组件可见之前加载。
我有这个模板:
<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 生命周期挂钩仅在用户显示组件时触发?
我会尝试:
- 将布尔类型的输入 属性 添加到
OtherComponent
组件。 - 将
show
的值传递给输入 属性,然后在OtherComponent
组件内部,使用ngOnChanges
检测输入 属性 中的任何变化并相应地调用load()
。