The problem concerns a client side Blazor compoenent. The component contains a div hidden by a component variable (bool opened).
I need the component to run some Javascript after the div has seen shown in the compoenent code file (in order to adjust it's position on the screen), code below should explain this a little better:
Component.razor
<div id="select-@Id" class="select-component" style="position: relative;">
<div class="option-selected" @onclick="@OnClick" style="border: 1px solid black;">
@if (opened)
{
<div class="options-wrapper" style="position: absolute; top: 30px; left: 0; border:1px solid red; background-color: white; z-index: 100;">
Sample Content
</div>
}
</div>
</div>
Component.razor.cs
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace Accounting.Web.Components.Select
{
public partial class Select
{
[Parameter]
public int Id { get; set; } = default!;
[Parameter]
public RenderFragment ChildContent { get; set; } = default!;
[Inject]
public IJSRuntime JSRuntime { get; set; }
private IJSObjectReference jsModule;
public bool opened = false;
public void OnClick()
{
opened = !opened;
if (opened)
{
jsModule.InvokeVoidAsync("adjustPosition", "select-" + Id);
}
}
protected override async Task OnInitializedAsync()
{
jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/test.js");
}
}
}
test.js
export function adjustPosition(node) {
console.log(node);
console.log($("#" + node + " .options-wrapper").length); // this always 0
}
The problem is that the div (.options-wrapper) which is shown in the OnClick event is not yet available when I Invoke the JS, therefore the JS script has no access to it.
I suspect this could potentially be solved by adding a timer in the JS script, however I was wondering if there was a less hackier solution available to my problem above?