When loading a Blazor page, I try to go to the end of a Virtualize list to display the last information (messages like a chat application).
So I have the following Blazor code:
<div id="messages-container" style="overflow-y: scroll; height:500px"><Virtualize Context="message" ItemsProvider="@GetMessages"><p>@message.Content</p></Virtualize></div><script> function scrollToBottom() { var objDiv = document.getElementById("messages-container"); objDiv.scrollTop = objDiv.scrollHeight; }</script><button onclick="scrollToBottom();">Manual scroll</button>How can I raise the JS scrollToBottom() function after the Virtualize has rendered the initial DOM of the first page of messages?
If I execute the scrollToBottom() JS function in the OnAfterRenderAsync() method of the page, the scroll does not work as expected, because:
- The
ItemsProvideris not called before theOnAfterRenderAsync()method. So no data is retrieved. - Because no data is retrieved, no DOM is rendered and the
messages-containeris empty and have ascrollHeightvalue defined to500.
protected override async Task OnAfterRenderAsync(bool firstRender){ await JSRuntime.InvokeVoidAsync("scrollToBottom");}However, after the first page is rendered by the Virtualize component, if I click the Manual scroll button, the Virtualize component is scrolled to the last page of the data (the scrollHeight value is defined in this case to 9845 for example).
How can I call the scrollToBottom() JS function after the first page of the Virtualize component has been rendered ?Or there is an other way to go to the bottom of a Virtualize component (last page) ?