在Angular中,可以使用ViewChild
和ElementRef
来滚动到动态创建的元素。以下是一个代码示例:
ViewChild
和ElementRef
来获取动态创建的元素,并使用scrollIntoView
方法滚动到该元素:import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('dynamicElement', { static: false }) dynamicElement: ElementRef;
scrollToDynamicElement() {
this.dynamicElement.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
在上面的示例中,点击按钮后,将滚动到动态创建的元素。ViewChild
装饰器用于获取具有指定标识符的元素,ElementRef
用于访问该元素的原生DOM对象。然后,使用scrollIntoView
方法将滚动到该元素,{ behavior: 'smooth', block: 'start' }
参数用于平滑滚动,并将元素对齐到视口的顶部。
请注意,ViewChild
装饰器的第二个参数{ static: false }
表示该元素是动态创建的,因此在AfterViewInit
生命周期钩子之前不会立即可用。