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>();
}
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); }
}
}
The way that Blazor compiler works now, you can inject C#
code on @ref
attribute. You can use it for adding the components to a list.
@for (int i = 0; i < 10; i++)
{
<MyComponent @ref="components.Add((MyComponent)__value);//" />
}
@code
{
List<MyComponent> components = new List<MyComponent>();
}
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);
}
}