Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add @ref to a Blazor component in a loop

How to add a @ref to Blazor components inside a loop?

@for (int i = 0; i < 10; i++)
{
    <MyComponent @ref="???"/> // I want to add this component to the list
}

@code
{
    List<MyComponent> components = new List<MyComponent>();
}
like image 287
Kahbazi Avatar asked Sep 12 '25 02:09

Kahbazi


2 Answers

My solution is as follows:

@for (int i = 0; i < 10; i++)
{ 
    <MyComponent @ref="ComponentRef" />
}

@code {
    List<MyComponent> ComponentRefs = new List<MyComponent>();
    MyComponent ComponentRef {
        set { ComponentRefs.Add(value); }
    }
}

Explanation

As the above did not work I found one simple solution. Add the component to an internal list on the ref setter. You can then reference the component via the index.

Example:

private List<MyComponent> components = new List<MyComponent>>();

        public MyComponent MyComponentRef
        {
            get
            {
                return null;
            }
            set
            {
                components .Add(value);
            }
        }
like image 38
user1029883 Avatar answered Sep 14 '25 15:09

user1029883



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!