Reputation: 923
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
Reputation: 45646
You can do it in a variety of ways. Here's one:
<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);
}
}
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>
@for (var i = 0; i < 10; i++)
{
var id = "dragDiv" + i.ToString();
<DynamicDiv ID="@id"></DynamicDiv>
}
Upvotes: 4