Articles in this section
Category / Section

How to bind component generated dynamically using RenderFragment?

2 mins read

This article explains how to bind component generated dynamically using RenderFragment

 

You can build Blazor render trees manually with RenderTreeBuilder  which provides methods for building and manipulating components manually in C# code. The following code explains how to bind value for DatePicker component which is generated dynamically using RenderFragment . Refer sequence 3, 4 where binding and call back is handled.

Index.razor

@using Syncfusion.Blazor.Calendars
@using Syncfusion.Blazor.Buttons
 
 
<div id="component-container">
    @dynamicComponent
</div>
 
<SfButton ID="dynamic-button" Content="Render DatePicker" @onclick="RenderComponent"></SfButton>
<SfButton ID="button" Content="Change Date" @onclick="onChange"></SfButton>
 
@code {
    public DateTime? DateValue { get; set; } = DateTime.Now.Date;
    private RenderFragment dynamicComponent { get; set; }
    private RenderFragment CreateComponent() => builder =>
    {
        builder.OpenComponent(0, typeof(SfDatePicker<DateTime>));
        builder.AddAttribute(1, "ID", "MyDynamicId");
        builder.AddAttribute(2, "Placeholder", "Choose a date");
        //Bind the value property with Datevalue property
        builder.AddAttribute(3, "Value", DateValue);
        builder.AddAttribute(4, "onchange", Microsoft.AspNetcore.Components.EventCallback.Factory.CreateBinder(this, _value => DateValue = _value, DateValue));
        builder.CloseComponent();
    };
 
    private void RenderComponent()
    {
        dynamicComponent = CreateComponent();
    }
    private void onChange()
    {
        DateValue = new DateTime(DateTime.Now.Year,DateTime.Now.Month,07);
       
    }
}
 

 

 

 

View Sample in GitHub

Refer to our documentation and online samples for more features. If you have any queries, please let us   know in the comments below. You can also contact us through our Support forum or Support ticket. We are happy to assist you!

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied