直接在模板中绑定scrollTop会产生错误

时间:2018-04-17 03:44:59

标签: angular

我正在开发一个Angular 5项目。在我的项目中,我有像元素一样的聊天框。我在ul中列出了评论,其高度由overflow-y: auto确定。像标准聊天框一样,我必须显示此可滚动ul的最底部。因此,当添加新评论时,它将位于ul的底部,我必须滚动到底部。为了实现这一点,我将此scrollTop的{​​{1}}属性绑定到ul,如下所示,

scrollHeight

我在初始化此组件并销毁此组件时收到错误<ul class="comment-list" #commentEl [scrollTop]="commentEl.scrollHeight"> <li *ngFor="let comment of comments">{{ comment }}</li> </ul> 。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

将ul标记包装在div元素中,并使用viewChild装饰器

引用dom

<强> HTML

<div style="height:200px;width:100%;overflow-y:auto" #commentEl [scrollTop]="scrolltop">
<ul class="comment-list">
    <li *ngFor="let comment of comments">{{ comment }}</li>
</ul>
</div>

<强> TS

@ViewChild('commentEl') comment : ElementRef ;  
scrolltop:number = null

并提供添加评论的位置

this.scrolltop = this.comment.nativeElement.scrollHeight

demo link

相关问题