Sowmyan Soman
Sowmyan Soman

Reputation: 923

Call JS function by passing dynamic elementref

How can we pass the html element controls created dynamically in OnAfterRenderAsync? My scenario is, I will have a foreach loop for the below control with unique ids. I need to call a JS function bypassing their reference. All documentation reference is talking about declaring them statically. Thanks for your help!

<div id="dragdiv" @ref="dragdiv" class="dragdiv">
    <div id="mydivheader" class="dragdivheader">Click here to move</div>
</div>

@code {

    private ElementReference dragdiv;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {

          if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync(
                    "dragElement", dragdiv);
            }

    }

}

Upvotes: 1

Views: 1269

Answers (1)

enet
enet

Reputation: 45646

You can do it in a variety of ways. Here's one:

  1. Define a component in which your div elements reside
  2. Define a parameter property named ID to store the ID of your referenced div. This value is passed from the location in which your component is instantiated.
  3. Inject IJSRuntime to perform JSInterop calls.
  4. Define the ElementReference variable
  5. Create a test method called ClickMe

DynamicDiv.razor

<div id="@ID" @ref="dragdiv" class="dragdiv">
    <div id="mydivheader" class="dragdivheader" @onclick="ClickMe">Click here to move</div>
</div>

@code {

    [Parameter]
    public string ID { get; set; }

    [Inject]
    public IJSRuntime JSRuntime { get; set; }
    private ElementReference dragdiv;

    private void ClickMe ()
    {
        JSRuntime.InvokeVoidAsync(
                "exampleJsFunctions.dragElement", dragdiv);
    }
}
  1. Create a JS method that is called when your div is clicked. Place this script at the bottom of the _Host.cshtml file, just below

    <script src="_framework/blazor.server.js"></script>

    <script> window.exampleJsFunctions = { dragElement: function (element) { // element; window.alert(element.id); } }; </script>

Usage

@for (var i = 0; i < 10; i++)
{
    var id = "dragDiv" + i.ToString();

    <DynamicDiv ID="@id"></DynamicDiv>
}

Upvotes: 4

Related Questions