Jacopo Sciampi
Jacopo Sciampi

Reputation: 3432

div that scroll at the bottom in Angular2

Sorry for the bad title, I really have no idea on how to write something that has sense in few words.

the situation is like this:

enter image description here

The div that scroll has this css:

.element-list{
  width:100%;
  max-height: 180px;
  overflow-y: auto;
}

the topBar has an height of 20px and the main wrapper is of 200px.

Inside the div that scroll, in the html, there is something like this (that's useless to you, but just for letting you understand better) :

<div class="something" *ngFor="let data of myData">
  <div>{{data.id}}</data>
</div>

This works fine, whenever I add something into myData is reflected into the ngFor so I see more and more <div>{{data.id}}</data>.

What I'm trying to achieve is to automatic scroll at the bottom whenever there are elements that trigger the overflow-y: auto;.

What I mean is: Since I have few elements(let's say, for example, ten elements), the scroll-bar is hidden. but when the elements are more than ten, the scroll bar appears, but it doesn't go to the bottom.

Like this:

enter image description here

As you can see there are more element. What I want, is that the div will auto-scroll to the bottom. So whenevener something is added it will always be like this:

enter image description here

Is there a way to do it in Angular or by scss/css?

Upvotes: 4

Views: 5071

Answers (1)

Pandiyan Cool
Pandiyan Cool

Reputation: 6565

call scrollBottom() after view completed using ngAfterViewChecked

working sample - click add button UI to experiment

html

<div style="height:200px; overflow-y:auto;" #scroll>
    <div *ngFor="let i of list">
        {{i.name}}
        <br>
    </div>
</div>


<button (click)="Add()">Add</button>

<button (click)="scrollToTop()">Scroll to top</button>
<button (click)="scrollBottom()">Scroll to bottom</button>

component

@ViewChild('scroll', { read: ElementRef }) public scroll: ElementRef<any>;

  ngAfterViewChecked() {
    this.scrollBottom()
  }

  public scrollBottom() {
    console.log(this.scroll.nativeElement.scrollTop);
    this.scroll.nativeElement.scrollTop = this.scroll.nativeElement.scrollHeight;

  }

  public scrollToTop() {
    this.scroll.nativeElement.scrollTop = 0;
  }

Upvotes: 8

Related Questions