How to set @ref for dynamically generated elements?

Platform: Blazor| Category: Components

To create a reference for dynamically generated components in Blazor, use the dictionary to create the reference for dynamically created elements at runtime.

[index.razor]

@page "/"

@foreach (var id in identifiers)
{
    <button @ref="myComponents[id]" @onclick="onclick">@id</button>
}

@code {
    private List<string> identifiers = new List<string> { "Button1", "Button2", "Button3" };
    private Dictionary<string, ElementReference> myComponents = new Dictionary<string, ElementReference>();
    private void onclick(MouseEventArgs args)
    {
        var d = myComponents;
        var a = args;
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.