直接在模板中绑定 scrollTop 会出错 [英] Binding scrollTop directly in template gives error

查看:23
本文介绍了直接在模板中绑定 scrollTop 会出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 Angular 5 项目.在我的项目中,我有类似元素的聊天框.我在 ul 中列出注释,它的高度用 overflow-y: auto 固定.就像标准聊天框一样,我必须显示此可滚动 ul 的最底部.因此,当添加新评论时,它将出现在 ul 的底部,我必须滚动到底部.为了实现这一点,我将这个 ulscrollTop 属性绑定到 scrollHeight 如下,

    <li *ngFor="let comment of comments">{{ comment }}</li>

我收到一个错误 ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改.以前的值:'851'.当前值:'0',同时初始化这个组件和销毁这个组件.我该如何解决这个问题?

解决方案

ul 标签包裹在 div 元素中,并使用 viewChild 装饰器引用 DOM.

HTML

<ul class="comment-list"><li *ngFor="let comment of comments">{{ comment }}</li>

TS

@ViewChild('commentEl') 评论:ElementRef;滚动顶部:数字 = 空;

并给出您添加评论的位置

this.scrolltop = this.comment.nativeElement.scrollHeight;

演示 link

I am working on an Angular 5 project. In my project I have chat box like element. I am listing the comments in a ul, its height is fixed with overflow-y: auto. Like a standard chat box I have to show the very bottom of this scrollable ul. So when a new comment is added it will be coming at the bottom of the ul and I have to scroll to the bottom. In order to achieve this I am binding the scrollTop property of this ul to the scrollHeight as follows,

<ul class="comment-list" #commentEl [scrollTop]="commentEl.scrollHeight">
    <li *ngFor="let comment of comments">{{ comment }}</li>
</ul>

I am getting an error ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '851'. Current value: '0' while initializing this component and destroying this component. How can I fix this issue?

解决方案

Wrap the ul tag in a div element and reference the DOM using viewChild decorator.

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;

And give where you add the comments

this.scrolltop = this.comment.nativeElement.scrollHeight;

demo link

这篇关于直接在模板中绑定 scrollTop 会出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆