Add/load components dynamically

asp.net-core blazor c#

Question

Good Blazor people, I need your help.

Today when adding components to a page, you normally do something like this:

@page "/somepage"

<MyComponent></MyComponent>

What I want to do is to add the components dynamically, something like this:

@page "/somepage"

@dynamicComponent

@functions{
 BlazorComponent dynamicComponent = Activator.CreateInstance<Components.MyComponent>();
}

Any ideas how to do this, adding or loading components dynamically?

Accepted Answer

There are no high level API's for this at the moment. You can use low level API's as explained here: https://github.com/aspnet/Blazor/issues/723

In your case this would translate to:

@page "/somepage"

@dynamicComponent()

@functions{
  RenderFragment dynamicComponent() => builder =>
    {
        builder.OpenComponent(0, typeof(SurveyPrompt));
        builder.AddAttribute(1, "Title", "Some title");
        builder.CloseComponent();
    };
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow