繁体   English   中英

单击 angular 8 滚动到页面顶部

[英]Scroll to top of the page with click in angular 8

我有 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 标题。

那么我必须改变什么?

谢谢你。

这是解决方案:

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

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

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



typescript/javascript 中的文档 object 有一个名为“scrollIntoView”的 function,可用于滚动到特定元素。 在您的情况下,您可以创建一个函数,如下面的代码片段所示:

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

希望这对你有帮助。 :-)

如果我理解正确,请更改以下部分:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM