Is there a way in Blazor to do render a component created in code?
Example usage:
Test.razor
<h4>Type: Test</h4>
<button @onclick="()=>{count++;}">Inc</button>
Count: @count
<br />
RandomCount: @ManualSet
@code
{
private int count = 0;
public int ManualSet { get; set; }
}
Counter.razor
<h3>Counter2</h3>
*** renderThisObject(_tests[active]); // Render blazor componant based on existing class. ***
<button @onclick="()=>cycleActive()">Change</button>
@code
{
int active = 0;
void cycleActive()
{
if (active < _ tests.Count() - 1)
{
active++;
return;
}
active = 0;
}
List<Test> _tests = new List<Test>();
protected override async Task OnInitializedAsync()
{
for (int i = 0; i < 10; i++)
{
var test = new Test();
test.ManualSet = i;
_tests.Add(test);
}
}
}
I’ve not specifically got a need to do this, but more of a curiosity at this point (see below for “work around”).
I also understand, it’s likely better to render all the components and just hide the ones not shown, thus not having to rebuild the the elements in the dom. Using keys can help here as well.
But if for example, we have a high memory object, and we want to keep memory usage low on the clients device, we could want re-render, rather than use hidden dom elements.
My existing work around is to do this:
Test.razor
<h4>Type: Test</h4>
<button @onclick="()=>{Data.Count++;}">Inc</button>
Count: @Data.Count
<br />
RandomCount: @Data.ManualSet
@code
{
TestModel _data;
[Parameter]
public TestModel Data { get;set;}
}
TestModel.cs // Create a class to hold all data used within the component
public class TestModel
{
public int Count { get; set; }
public int ManualSet { get; set; }
}
Counter.razor
@page "/counter3"
<h3>Counter3</h3>
<div>
<DynamicComponent Type="_tests[active].Type" Parameters="_tests[active].Params" />
</div>
<button @onclick="()=>cycleActive()">Change</button>
@code
{
int active = 0;
void cycleActive()
{
if (active < _tests.Count() - 1)
{
active++;
return;
}
active = 0;
}
List<TabItem> _tests = new List<TabItem>();
class TabItem
{
public Type Type;
public Dictionary<string, object> Params;
public string TabTitle;
public string TabKey;
}
protected override async Task OnInitializedAsync()
{
for(int i =0; i < 10; i ++)
{
var tabData = new TestModel();
tabData.ManualSet = (_tests.Count() + 1);
var tab = new TabItem();
tab.TabKey = Guid.NewGuid().ToString();
tab.TabTitle = "Tab " + (_tests.Count() + 1);
tab.Type = typeof(Test);
tab.Params = new Dictionary<string, object>() { ["Data"] = tabData };
_tests.Add(tab);
}
}
}