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>();
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With