简体   繁体   English

单击 angular 8 滚动到页面顶部

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

I have angular 8 application.我有 angular 8 应用程序。

And I have navigation buttons for next and previous.我有下一个和上一个的导航按钮。 But so I want to archieve that you will be navigate to top of the page when next is triggerd.但是,所以我想存档,当下次触发时,您将导航到页面顶部。

So I have this:所以我有这个:

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

and ts file:和 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 );
  }



But I don't get error.但我没有得到错误。 But also it is not navigating to top of page.但它也没有导航到页面顶部。 IN this case the h4 heading.在这种情况下,h4 标题。

So what I have to change?那么我必须改变什么?

Thank you.谢谢你。

This is the solution:这是解决方案:

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

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

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



The document object in typescript/javascript, has a function called "scrollIntoView", which can be used to scroll to a specific element. typescript/javascript 中的文档 object 有一个名为“scrollIntoView”的 function,可用于滚动到特定元素。 In your case you could created a functions as seen on the snippet below:在您的情况下,您可以创建一个函数,如下面的代码片段所示:

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

Hope that was helpful to you.希望这对你有帮助。 :-) :-)

If I understand you correctly, change the following section:如果我理解正确,请更改以下部分:

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

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

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