3

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

2 Answers 2

3

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)}">
....
Sign up to request clarification or add additional context in comments.

Comments

1

It should work with something like

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

or using external dependency ngx-scroll-to

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.