Reputation: 491
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.
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?
Upvotes: 3
Views: 11456
Reputation: 16820
[Temp quick fix] Adding timer worked for me,
ngAfterViewChecked() {
setTimeout(this.scrollBottom(), 500)
}
Upvotes: 1
Reputation: 6565
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;
}
Upvotes: 5
Reputation: 39
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">
Upvotes: 1