0

I'm trying to use scrollIntoView() for my Angular 2 project. I have a container div with overflow that grow when data arrives to the component and I need to scroll to the bottom of the div as data arrives. If I use a button and pass the reference through it, this work fine.

Example:

<div class="container">
<button (click)="scrollTo(target)"></button>
-----
-----
<!-- Dynamic content here -->
-----
-----
<div #target class="target" id="target"></div>

And in the component:

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

The problem is that I don't want to use a button, I need to call the scrollTo function within the component. I have tried to use to use @ViewChildren, document.querySelector and document.getElementById but nothing works.

Example:

1)

@ViewChildren('target') target: ElementRef;

And in the function:

public scrollTo() {
    this.target.nativeElement.scrollIntoView({behavior: 'smooth'});
}

2)

public scrollTo() {
    let element = document.getElementById('target');
    element.scrollIntoView({behavior: 'smooth'});
}

3)

public scrollTo() {
    let element = document.querySelector('.target');
    element.scrollIntoView({behavior: 'smooth'});
}

En all cases if I print the element by console, the result is the same:

<div class="target" id="target" _ngcontent-ema-86=""></div>

But the scroll goes to the bottom of the container div only with the button.

Additional data: The project is a VSTO add-in for PowerPoint and it should run on IE11. Thanks for your help.

2 Answers2

0

Maybe the problem due to smooth behavior support in IE11. Have you tried without it?

enter image description here

AlexanderFSP
  • 652
  • 4
  • 10
-1

You need to use ViewChild not ViewChildren. ViewChild is used when you want to access a single element from the template. ViewChildren is used when you have multiple elements in the template with the same id (#target). The latter will give you an array.

Try this instead.

@ViewChild('target', { static: true }) target: ElementRef;

public scrollTo() {
    this.target.nativeElement.scrollIntoView({behavior: 'smooth'});
}

Check out the docs for more details on ViewChild.

nash11
  • 8,220
  • 3
  • 19
  • 55