简体   繁体   中英

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

It should work with something like

scroll(el: HTMLElement) {
 el.scrollIntoView({behavior: 'smooth'});
}

or using external dependency ngx-scroll-to

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)}">
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM