javascript - 如何滚动到Angular Tree中的选定节点
问题描述
我有一个带有 Angular Tree 组件的页面。单击主仪表板上的特定元素时,树节点会“聚焦”。我通过使用 this.tree.treeModel.setFocusedNode(node) 来做到这一点,但它也应该滚动到匹配的节点。不幸的是,滚动没有发生。是否有任何方法可以滚动到突出显示/聚焦的元素?
对此有任何帮助吗?
解决方案
Oussama 建议的 scrollIntoView 确实有效,让该元素调用 scrollIntoView 只是有点棘手。一种方法是将类分配给选定节点,然后使用 document.querySelector 找到它,例如
在树组件中:
set selected(value: YourObjectType) {
if (this._selected !== value) {
this._selected = value;
if (this._selected) {
//implement findallParents in your model, then expand tree up to the item to be selected
this._selected.findAllParents.forEach(m => this.treeControl.expand(m));
//wait till all nodes are expanded - there might be a better way to do this
setTimeout(() => {
const element = document.querySelector('.selected-node');
if (element) {
element.scrollIntoView({behavior: 'smooth'});
}
});
}
}
}
isSelected(node: YourObjectType) {
return this._selected === node;
}
在模板中:
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
<mat-nested-tree-node *matTreeNodeDef="let node;">
<li [ngClass]="{'selected-node': isSelected(node)}">
....