我的HTML中有一个id为footerWrapperTop
的div。
我的组件中有以下TypeScript:
ngAfterViewInit(): void {
try {
this.sFragment = 'footerWrapperTop';
const nativeElement = document.querySelector('#' + this.sFragment);
nativeElement.scrollIntoView();
} catch (e) { } }
但是,页面在运行时不会向下滚动到页脚。我做错了什么?
如果Iconsole.dir(nativeElement);
,它将在控制台中显示DIV。
您可以使用Angular的渲染器
根据Angular的官方文档为selectRootElement提供第二个参数,因为它用于保存您的内容
语法:
selectRootElement(selectorOrNode: any, preserveContent?: boolean): any
为您的参考创建了Stacklitz演示
import { Component, AfterViewInit, Renderer2 } from '@angular/core';
@Component({...})
export class ChildComponent implements AfterViewInit {
sFragment: string;
constructor(private renderer: Renderer2) {}
ngAfterViewInit(): void {
this.sFragment = 'footerWrapperTop';
const element = this.renderer.selectRootElement(`#${this.sFragment}`, true); // true to indicate that you will preserve the content
element.scrollIntoView({ behavior: 'smooth' }); // for smooth scrolling
}
}
请检查这个问题:如何在angular 2+中的元素上调用scrollIntoView
首先在元素(#footerWrapperTop(中添加一个模板引用变量:
<div #footerWrapperTop></div>
在组件中.ts:
export class MyComponent {
@ViewChild("footerWrapperTop") MyProp: ElementRef;
ngAfterViewInit() {
this.MyProp.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
然而,当路由器发生变化时,angular 5及更低版本会出现错误。Angular 6已经解决了这个问题。检查此问题:https://github.com/angular/angular/issues/7791
角度的用户渲染器2
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div #targetDiv style="height: 1000px;"></div>
<button (click)="scrollToDiv()">Scroll to Div</button>
`
})
export class AppComponent {
@ViewChild('targetDiv') targetDiv: ElementRef;
constructor(private renderer: Renderer2) {}
scrollToDiv() {
this.renderer.setProperty(window, 'scrollTo', {
top: this.targetDiv.nativeElement.offsetTop,
behavior: 'smooth'
});
}
}