【问题标题】:How to run function after a component became visible in Angular 8?组件在 Angular 8 中可见后如何运行函数?
【发布时间】: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


【解决方案1】:

我会尝试:

  • 将布尔类型的输入属性添加到OtherComponent 组件。
  • show 的值传递给输入属性,然后在OtherComponent 组件内,使用ngOnChanges 检测输入属性的任何变化并相应地调用load()

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2019-02-18
    • 2021-12-30
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多