可以使用Angular的ViewChild装饰器配合ElementRef类来实现此功能。首先,在template中添加一个#list的模板引用变量,并在ts文件中通过@ViewChild装饰器引用这个变量。
-
{{ item }}
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
items = ['One', 'Two', 'Three'];
@ViewChild('list', { static: false }) list: ElementRef;
addItem(newItem: string, index: number) {
this.items.splice(index, 0, newItem);
this.scrollToIndex(index);
}
scrollToIndex(index: number) {
const listEl = this.list.nativeElement;
const itemEl = listEl.children[index];
itemEl.scrollIntoView({behavior: 'smooth'});
}
}
然后,在添加项目的方法中调用scrollToIndex方法,将新的项目滚动到特定的索引位置。