当“可观察”完成时,将div滚动到底部

devpato

我有一条divwith消息,我想确保何时已检索到所有聊天信息以将div向下滚动到底部到最后一条消息,但是它不起作用,因此出现此错误:

无法读取null的属性'scrollHeight'

TS CHAT组件

 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()console后,我在网页上看到的一切,它工作正常。因此,问题在于正在获取触发器,而Observable尚未完成。也许?

我的问题与我在SO上看到的其他解决方案不同,因为它们未使用可观察的元素,而在触发可观察的元素时该元素尚不存在。

更新:

我尝试使用accesing元素,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>
devpato

最终能够获得解决方案:

解决方案1)

 <div  class="card-body msg_card_body" id="card-body" #cardBody
  [scrollTop]="cardBody.scrollHeight">
 .
 .
 </div>

解决方案2)

ngAfterViewInit() {
    setTimeout(() => {
     this.scrollBottom();
    }, 500);  
}
scrollBottom() {
  const CHAT_BODY = document.getElementById("card-body");
  CHAT_BODY.scrollTop = CHAT_BODY.scrollHeight;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章