加载组件后滚动到 Material Accordion 中的特定扩展面板

Ent*_*ain 5 typescript angular-material angular

我们正试图滚动到一个特定<mat-expansion-panel>内的项目<mat-accordion>。问题是ngAfterViewInit()在手风琴及其面板完全加载之前触发。这意味着在scrollIntoView()加载手风琴时调用该函数,然后页面大小发生变化,使我们的滚动操作将我们带到错误的页面位置。

我们还尝试了其他生命周期钩子,但没有帮助,因为它们都被提前调用了。有人对这个问题有什么好的做法吗?

我们的源代码很简单,因为我们正在尝试实现一些非常基本的东西:

登陆页面.component.html

<mat-accordion>
   <mat-expansion-panel id="pangel-1">
    <mat-expansion-panel-header>
      <mat-panel-title>Lorem ipsum</mat-panel-title>
    </mat-expansion-panel-header>
    <p>
      Lorem ipsum dolor sit amet,
      consetetur sadipscing elitr,
      sed diam nonumy eirmod tempor invidunt...
    </p>
  </mat-expansion-panel>
  <mat-expansion-panel id="panel-2">
    <mat-expansion-panel-header>
      <mat-panel-title>Lorem ipsum</mat-panel-title>
    </mat-expansion-panel-header>
    <p>
      Lorem ipsum dolor sit amet,
      consetetur sadipscing elitr,
      sed diam nonumy eirmod tempor invidunt...
    </p>
  </mat-expansion-panel> 

  [ ... ] // more panels

</mat-accordion>
Run Code Online (Sandbox Code Playgroud)

登陆页面.component.ts

ngAfterViewInit() {
  this.scroll("panel-1");
}

scroll(id) {
  console.log(`scrolling to ${id}`);
  let el = document.getElementById(id);
  el.scrollIntoView();
}
Run Code Online (Sandbox Code Playgroud)

G. *_*ter 3

这是StackBlitz上使用 Angular Material 7 的示例。您的技术效果很好,但您需要注意一些事情 - 确保页面足够长,以便面板可以位于页面顶部,并确保面板的 ID 没有拼​​写错误。