在角8中点击滚动到页面顶部。

问题描述 投票:0回答:1

我有一个Angular 8应用程序。

我有下一个和上一个的导航按钮。但是我想实现当下一个按钮被触发时,你会被导航到页面顶部。

所以我有这个。

 <h4 id="heading"  #goUp class="echeq-title">{{ currentEcheqPage.title }}</h4>

和ts文件。

export class EcheqPageComponent implements OnInit, AfterViewInit {

  @Input() currentEcheqPage: EcheqPage;
  @Input() currentEcheqPager: EcheqPager;
  @ViewChild('goUp', {static: false}) contentPage: ElementRef;

  // We use template variables to query the components
  @ViewChildren('echeqElement') elementComponents: QueryList<EcheqElementComponent>;

  EcheqElement = EcheqElement;
  elementsChanged = true;
  container: HTMLElement;

  constructor( private echeqService: EcheqService ) { }

  ngOnInit() {
    // document.getElementById ('heading').scrollIntoView();
  }

  ngAfterViewInit(): void { 
    this.showUp();

  }
}

private showUp(): void {
    this.contentPage.nativeElement.scrollTo( 0, 0 );
  }



但我没有收到错误信息 但它也没有导航到页面顶部。在这种情况下,h4标题。

所以我必须改变什么?

谢谢你,我有Angular 8应用程序。

javascript angular typescript
1个回答
0
投票

typecriptjavascript中的文档对象有一个叫做 "scrollIntoView "的函数,它可以用来滚动到一个特定的元素。在你的情况下,你可以创建一个函数,如下面的片段所示。

showUp() {
    const element = document.querySelector('#goUp');
    element.scrollIntoView();
}

希望这对你有帮助 :-)


1
投票

如果我的理解是正确的,请修改以下部分。

 private showUp(): void {
    window.scroll(0,0);
  }

0
投票

这就是解决方案

  @ViewChild('goUp', { static: true }) contentPage: ElementRef;

 ngOnChanges(): void {
   this.showUp();
  }

  showUp() {
     this.contentPage.nativeElement.scrollIntoView();
  }



© www.soinside.com 2019 - 2024. All rights reserved.