Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/load components dynamically

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?

like image 357
gorhal Avatar asked Aug 28 '26 05:08

gorhal


1 Answers

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();
    };
}
like image 61
MartinH Avatar answered Aug 29 '26 18:08

MartinH



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!