Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to selected node in Angular Tree

I have a page with Angular Tree Component. The tree node gets "focused" on click of a specific element on the main dashboard. I an doing this by using this.tree.treeModel.setFocusedNode(node) but it should also scroll to the matching node. Unfortunately the scrolling is not happening. Is there any method available to scroll to the highlighted/focused element?

Is there any Any help on this is appreciated

like image 433
Yogesh Avatar asked May 03 '26 15:05

Yogesh


1 Answers

the scrollIntoView suggested by Oussama actually works, it's only a bit tricky to get that element to call scrollIntoView on. One way would be to assing a class to selected node and then use document.querySelector to find it, like

in Tree component:

   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;
      }

in template:

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
              <mat-nested-tree-node *matTreeNodeDef="let node;">
                <li [ngClass]="{'selected-node': isSelected(node)}">
....
like image 59
user656449 Avatar answered May 06 '26 04:05

user656449