0

只有当用户看到加载数据的特定组件时,我才想加载数据。所以不要在组件可见之前加载。

我有这个模板:

<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 生命周期钩子仅在用户显示组件时触发?

4

1 回答 1

0

我会尝试:

  • 向组件添加布尔类型的输入属性OtherComponent
  • 将值传递show给输入属性,然后在OtherComponent组件内部,ngOnChanges用于检测输入属性的任何变化并load()相应地调用。
于 2020-01-13T15:33:03.113 回答