简体   繁体   中英

Scroll Top not working correctly in angular2

I have created a table where rows get populated dynamically. I have a add button where i can add rows as well. Here i want to show newly added row in the table at the bottom after i add an row,so i am using the below code is component.ts.

this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;

But the above code doesn't seems to work properly. The problem is that when i add a new row,scroll is not completely going to the bottom of div tag, hence new row cannot be seen.

Below is my html code where i am using a table inside a div tag as shown below.

<div style="height:200px;overflow-y:auto">
    <table class="table table-bordered table-hover">
        <thead>
        <tr class="d-flex">
            <th class="col-3">Q.No</th>
            <th class="col-4">Record Answer</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let answer of answerPaper; let i = index" class="d-flex">
            <td class="col-3">answer.no</td>
            <td class="col-4">answer.name</td>
        </tr>
        </tbody>
    </table>
</div>
<button (click)="addrow()">Add Row</button>

Below is the component.ts

public addRow(){
    this.answerPaper.push({});
}

I am posting the image of scrollbar also.

当我添加新行时,滚动条没有完全移动到 div 的底部,因此没有完全看到新添加的行

When i add a new row,scroll bar is not completely moving to the bottom of div hence newly added row is not seen completely

Am i going wrong somewhere?

Call your scroll to top or bottom once angular element is ready

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

  ngAfterViewChecked() {
    this.scrollBottom()
  }

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

SLACKBLITZ

In my case I wanted to scroll down on a comment list when a new comment is added.
But the logic is the same.
I define a variable scrollDown: number; and I recover the comment list like this:

@ViewChild('commentList') commentList: ElementRef;

Then, when the comment is added:

this.scrollDown = this.commentList.nativeElement.scrollHeight;

Finally, in the template:

<div #commentList class="document-comments-list" [scrollTop]="scrollDown">

[Temp quick fix] Adding timer worked for me,

ngAfterViewChecked() {
  setTimeout(this.scrollBottom(), 500)
}

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