I have a list component in blazor which has a collapsable create section, I want when you click to show the create section that it will display and scroll to the create section. My issue is that StateHasChanged() doesn't update the UI in time, so the element we're trying to scroll to doesn't exist yet when the javascript fires.
Obviously I can get around this with a timeout, but what is a cleaner way to do this in Blazor? Is there a way to say something like await StateUpdated()....
My code looks something like this:
@page "/createlist"
<div>
<h3>My List</h3>
<a @onclick="ToggleAdding">
Create New
</a>
</div>
<ul>
@* list existing items... *@
</ul>
@if (IsAdding)
{
<div id="some-create-id">
<h3>Add Section</h3>
@* create controls here *@
</div>
}
@code {
public void ToggleAdding()
{
IsAdding = !IsAdding;
// Need something similar to StateHasChanged(), that is awaitable.
JsRuntime.InvokeVoidAsync("ScrollIn", new object[] { CreateElementId });
}
}
And the js is simply:
ScrollIn = id => {
let element = document.getElementById(id);
console.log(!!element ? "SCROLLIN" : "NO FOUND ELE", id);
if (!!element) { element.scrollIntoView(); }
}