I have a div
with messages and I want to make sure when all the chat information has been retrieve to scroll the div down to the bottom to the last message, but it doesn't work it gives me this error:
Cannot read property 'scrollHeight' of null
TS CHAT COMPONENT
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;
}
Notes:
The card-body
element is being loaded by the chat$ | async
I have tried to use finallize()
, and ngAfterViewInit()
and no luck. BUT if I copy past my code from the scrollBottom()
in the console
after I see everything on the page, it works fine. So the problem is that is getting trigger and the Observable it's not done yet. maybe?
My question is different than other solutions I have seen on SO because they aren't using observable an the element don't exist yet when the observable is being triggered.
UPDATE:
I Tried accesing the element using ViewChild
and got this error:
I got this error: property 'nativeElement' of undefined
@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>