【发布时间】:2019-01-13 19:23:25
【问题描述】:
我有一个带有消息的div,我想确保何时检索到所有聊天信息以将 div 向下滚动到最后一条消息的底部,但它不起作用,它给了我这个错误:
无法读取 null 的属性“scrollHeight”
TS 聊天组件
ngOnInit() {
this.chat$ = this._cs.joinUsers(source).pipe(tap(() => this.scrollBottom()));
}
scrollBottom() {
const CHAT_BODY = document.getElementById("card-body");
CHAT_BODY.scrollTop = CHAT_BODY.scrollHeight;
}
注意事项:
card-body 元素正在由 chat$ | async 加载
我曾尝试使用finallize() 和ngAfterViewInit(),但没有成功。 但是如果我在看到页面上的所有内容后从scrollBottom() 中的scrollBottom() 复制过去的代码,它可以正常工作。所以问题是正在触发,而 Observable 还没有完成。也许?
我的问题与我在 SO 上看到的其他解决方案不同,因为它们没有使用 observable 并且在触发 observable 时元素还不存在。
更新:
我尝试使用 ViewChild 访问元素并收到此错误:
我收到此错误:未定义的属性“nativeElement”
@ViewChild("cardBody")
cardBody: ElementRef;
ngAfterViewInit() {
console.log("Values on ngAfterViewInit():");
console.log(this.cardBody.nativeElement );
}
HTML
<ng-container *ngIf="(chat$ | async) as chat">
<ng-container *ngIf="(auth.user$ | async) as user">
.
.
<div class="card-body msg_card_body" id="card-body" #cardBody>
.
.
.
</div>
</ng-container>
</ng-container>
【问题讨论】:
-
啊抱歉,没看懂,是我的错。您是否尝试过使用
@ViewChild来获取组件?那应该给你一个“安全”的参考。 angular.io/api/core/ViewChild -
我明白了,这意味着未正确选择视图子项。您能否将设置为“card-body”的模板添加到问题中?
-
请在 HTML 标记中提供更多上下文,特别是如果
cardBody在ngFor或ngIf指令内。