【发布时间】:2019-12-11 18:20:52
【问题描述】:
我有一个带有 Angular Tree 组件的页面。单击主仪表板上的特定元素时,树节点会“聚焦”。我通过使用 this.tree.treeModel.setFocusedNode(node) 来做到这一点,但它也应该滚动到匹配的节点。不幸的是,滚动没有发生。是否有任何方法可以滚动到突出显示/聚焦的元素?
对此有什么帮助吗
【问题讨论】:
标签: javascript angular
我有一个带有 Angular Tree 组件的页面。单击主仪表板上的特定元素时,树节点会“聚焦”。我通过使用 this.tree.treeModel.setFocusedNode(node) 来做到这一点,但它也应该滚动到匹配的节点。不幸的是,滚动没有发生。是否有任何方法可以滚动到突出显示/聚焦的元素?
对此有什么帮助吗
【问题讨论】:
标签: javascript angular
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)}">
....
【讨论】:
它应该适用于类似的东西
scroll(el: HTMLElement) {
el.scrollIntoView({behavior: 'smooth'});
}
或使用外部依赖ngx-scroll-to
【讨论】: