我有一个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应用程序。
typecriptjavascript中的文档对象有一个叫做 "scrollIntoView "的函数,它可以用来滚动到一个特定的元素。在你的情况下,你可以创建一个函数,如下面的片段所示。
showUp() {
const element = document.querySelector('#goUp');
element.scrollIntoView();
}
希望这对你有帮助 :-)
如果我的理解是正确的,请修改以下部分。
private showUp(): void {
window.scroll(0,0);
}
这就是解决方案
@ViewChild('goUp', { static: true }) contentPage: ElementRef;
ngOnChanges(): void {
this.showUp();
}
showUp() {
this.contentPage.nativeElement.scrollIntoView();
}