Edoardo
Edoardo

Reputation: 475

Render blazor components dynamically from a factory

I have an IList<IControl> that is an interface that derives from IComponent, every implementation of the interface inherits from ComponentBase. The component is instantiated from a factory dynamically (it returns a component compatible with input's type).

Now I want to render this list, but I do not know how, this is my ControlsContainer.razor:

@foreach (var control in OrderedControls)
{
    <div @[email protected]().ToString()>

        @RenderWidget(control)

    </div>
}

I want to avoid a switch/if-else if with every component type (they are loaded dynamically with reflection, I do not need to register them somewhere).

Upvotes: 0

Views: 1088

Answers (1)

Neil W
Neil W

Reputation: 9112

Untested, but the following should work, or at least put you on the right path ...

@foreach (var control in OrderedControls)
{
    <div @[email protected]().ToString()>

        @RenderWidget(control)

    </div>
}

@code {
    RenderFragment RenderWidget(IControl control)
    {
        var concreteType = control.GetType();
        RenderFragment frag = new RenderFragment(b =>
        {
            b.OpenComponent(1, concreteType);
            b.CloseComponent();
        });
        return frag;
    }
}

Upvotes: 1

Related Questions