gorhal
gorhal

Reputation: 459

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?

Upvotes: 3

Views: 3934

Answers (2)

Paul M Sorauer
Paul M Sorauer

Reputation: 747

Update as this thread has a high Google rank...

Take a look at the new DynamicComponent control in ASP.NET Core Blazor and MVC 6.0. (To be released in .NET 6.0 and currently available in preview):

https://www.daveabrock.com/2021/04/08/blazor-dynamic-component/

Upvotes: 0

MartinH
MartinH

Reputation: 1490

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();
    };
}

Upvotes: 3

Related Questions