I don't know if its possible, but i have a switch statement allowing to different components based on the value. However i can see that i would like to use this switch statement, is there an option in blazor to reuse it?
This is the code i am thinking
@page "/"
@foreach (var widget in _components)
{
switch (widget)
{
case WidgetA:
<WidgetA/>
break;
case WidgetB:
<WidgetB/>
break;
}
}
However I would like to use it multiple time, is there a way to store this in a function I try the follow, but it doesnt load
<div class="row">
<div class="col-md-6">
@foreach (var widget in _components21)
{
switche(widget);
}
</div>
<div class="col-md-6">
@foreach (var widget in _components22)
{
switche(widget);
}
</div>
</div>
private string switche(IComponent widget)
{
string html = "";
switch (widget)
{
case WidgetA:
html = "<WidgetA/>";
break;
case <WidgetB/>:
html = "<WidgetB/>";
break;
}
return html;
}
CodePudding user response:
You could create a parent component that houses both widgets, then in the property of the parent component you can have a parameter called WidgetType that defines what widget you actually want to use.
Parent Widget:
@if(WidgetType == "A"){
<WidgetA>
}else{
<WidgetB>
}
@code{
[Parameter] public string WidgetType {get; set;}
}
Then in you would use this in your for loop
@foreach (var widget in _components)
{
<ParentWidget @WidgetType=widget.WidgetType>
}