Render blazor components dynamically from a factory - c#

I have an IList<IControl> that is an interface that derives from IComponent, every implementation of the interface inherits from ComponentBase. The component is instantiated from a factory dynamically (it returns a component compatible with input's type).
Now I want to render this list, but I do not know how, this is my ControlsContainer.razor:
#foreach (var control in OrderedControls)
{
<div #key=#Guid.NewGuid().ToString()>
#RenderWidget(control)
</div>
}
I want to avoid a switch/if-else if with every component type (they are loaded dynamically with reflection, I do not need to register them somewhere).

Untested, but the following should work, or at least put you on the right path ...
#foreach (var control in OrderedControls)
{
<div #key=#Guid.NewGuid().ToString()>
#RenderWidget(control)
</div>
}
#code {
RenderFragment RenderWidget(IControl control)
{
var concreteType = control.GetType();
RenderFragment frag = new RenderFragment(b =>
{
b.OpenComponent(1, concreteType);
b.CloseComponent();
});
return frag;
}
}

Related

Passing reference of component to its ChildContent components

To add some context, I'm trying to create a Dropdown select Blazor component. I've managed to create a concept of this entirely with CSS, #onclick, and #onfocusout.
I'm trying to pass a reference of the DropDown component to its children, DropDownItem. The only way I know how to achieve this, is by using the #ref and passing it as a parameter to the DropDownItem component.
<DropDown #ref="DropDownReference">
<DropDownItem ParentDropDown=#DropDownReference>Hello</DropDownItem>
<DropDownItem ParentDropDown=#DropDownReference>World</DropDownItem>
</DropDown>
There has to be a cleaner approach here that does not require manually passing the reference down to each child instance. I suppose I could use CascadingValue but that will still require me to store the DropDown reference.
I'm trying to notify DropDown parent when a click event occurs in DropDownItem. This will signal the parent to changes it selected value - as it would traditionally work in a select.
Here is an example of how you could do it using CascadingValue. The DropDownItem component will accept a [CascadingParameter] of type DropDown. There is nothing wrong in doing that, this is how it's done in most (if not all) component libraries.
DropDown.razor
<CascadingValue Value="this" IsFixed="true">
#* Dropdown code *#
<div class="dropdown">
#ChildContent
</div>
</CascadingValue>
#code {
[Parameter] public RenderFragment ChildContent { get; set; }
private string selectedItem;
public void SelectItem(string item)
{
selectedItem = item;
StateHasChanged();
}
}
DropDownItem.razor
#* Dropdown item code *#
<div class="dropdown-item" #onclick="OnItemClick">...</div>
#code {
[CascadingParameter] public DropDown ParentDropDown { get; set; }
[Parameter] public string Name { get; set; }
private void OnItemClick()
{
ParentDropDown.SelectItem(Name);
}
}
Usage:
<DropDown>
<DropDownItem Name="Hello">Hello</DropDownItem>
<DropDownItem Name="World">World</DropDownItem>
</DropDown>

Blazor Closes the div tag on a conditionally div wrapper

Im trying to wrap one of my components on some specific tag based on some conditions.
To make it simple lets say that i have a
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
And if 'condition' == true then it should wrap it in another div the result should be like this
<div class="wrapper-class">
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
</div>
And before you say, use if-else method. i must say no. because the tag and the class in it is dynamic so i cant write it like that.
What i tried to do is
#if (condition)
{
#:<div class="wrapper-class">
}
<div class="inner-class">
this must be in inner-class div and wrapped in some-class div
</div>
}
#if (condition)
{
#:</div>
}
I Thought it should do the job.
But the problem is the browser closes the outer div before putting the inner div in it.
You have to use BuildRenderTree
With BuilderRenderTree you have full control to build component html.
For more information read this good article Building Components Manually via RenderTreeBuilder
I ended up writing a wrapper component similar to this to solve this problem pretty elegantly:
#if (Wrap)
{
<div id="#Id" class="#Class">
#ChildContent
</div>
}
else
{
#ChildContent
}
#code
{
[Parameter] public string? Id { get; set; }
[Parameter] public string? Class { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
[Parameter] public bool Wrap { get; set; }
}
It doesn't support dynamic tag types, but that would be pretty easy to create using a component implementing BuildRenderTree as mRizvandi suggested.
If it's a simple layout like you've described than you can make use of the MarkupString. The trick is understanding that MarkupString will automatically close any tags that are left open. Therefore you just need to build the entire string properly before trying to render it as a MarkupString.
#{ bool condition = true; }
#{ string conditionalMarkup = string.Empty; }
#if (condition)
{
conditionalMarkup = "<div class=\"wrapper-class\">";
}
#{ conditionalMarkup += "<div class=\"inner-class\"> this must be in inner-class div and wrapped in some-class div </div>"; }
#if (condition)
{
conditionalMarkup += "</div>";
#((MarkupString)conditionalMarkup)
}
else
{
#((MarkupString)conditionalMarkup)
}
I do this for building simple conditional markup. Usually inside of an object iteration making use of String.Format to fill in property values.

Two way data-binding inside blazor template

I would like to use a two-way databinding between a component inside a template and its parents. The one way data binding is working well. But when I modified the Context passed from the RenderFragment this modification is not propagate to the template (container). Here is the example.
This it the template definition. We have a form and we want to be able to specify the content of the form in function of the model.
#typeparam TItem
#typeparam TItemDtoCU
#typeparam TDataService
<EditForm Model="#Item" OnValidSubmit="HandleValidSubmit" class="item-editor">
<DataAnnotationsValidator />
#FormContentTemplate(Item)
<span class="save">
<MatButton Type="submit" Raised="true">Save</MatButton>
<MatButton Type="reset" Raised="true" OnClick="HandleCancelSubmit">Cancel</MatButton>
</span>
</EditForm>
Here is the place where I use this template
<ModelEditorTemplate TItem="ClassName"
TItemDtoCU="OtherClassName"
TDataService="ServiceClassName"
ItemId="SelectedItem?.Id"
OnItemAdded="ItemAdded"
OnItemUpdated="ItemUpdated">
<FormContentTemplate>
<span>
<MatTextField Label="Name" #bind-Value="context.Name" #bind-Value:event="onchange" />
<ValidationMessage For="#(() => context.Name)" />
</span>
</FormContentTemplate>
</ModelEditorTemplate>
When the user modified the MatTextField field is reset to the initial value provided by the template component.
Do you have an idea ?
Edit 1 : More information about the way we fetched the data
Yes the TDataService is fetching the component from a REST Api. Here the partial class linked to the template :
public partial class ModelEditorTemplate<TItem, TItemDtoCU, TDataService> : ParentThatInheritsFromComponentBase
where TItem : BaseEntity, new()
where TDataService : ICrudService<TItem, TItemDtoCU>
{
public TItem Item = new TItem();
[Inject]
protected TDataService DataService { get; set; }
protected override async Task OnParametersSetAsync()
{
//...
await LoadItem();
// ...
}
protected async Task LoadItem()
{
//...
Item = await DataService.Get(ItemId.Value);
// ....
}
}
When the field inside FormContentTemplate RenderFragment update the model, it triggers the OnParametersSetAsync method of the template ,which fetch again the data from the server, update the model and then overwrite the modification done by the user.
There was no issue, with the form input inside the template just bad understanding of how it works.
I corrected the problem by using the SetParametersAsync to check if the parameter that change was the one, I was looking for and not the RenderFragment. The ItemId is the id of the record, I fetch from the DataService.
public override async Task SetParametersAsync(ParameterView parameters)
{
_hasIdParameterChange = false;
if(parameters.TryGetValue(nameof(ItemId), out int? newItemIdValue))
{
_hasIdParameterChange = (newItemIdValue != ItemId);
}
await base.SetParametersAsync(parameters);
}

Templating Blazor Components

Just thinking about coming up with a templated blazor component to do a CRUD style Single Page App which can have a specific object passed in so I don't have to write the same boilerplate code over and again.
so for instance as below parts of it can be templated by using RenderFragment objects:
#typeparam TItem
<div>
#if (AddObjectTemplate != null)
{
#AddObjectTemplate
}
else
{
<div style="float:left">
<button class="btn btn-primary" #onclick="AddObject">Add Object</button>
</div>
}
</div>
#code {
[Parameter]
public RenderFragment AddObjectTemplate { get; set; }
[Parameter]
public IList<TItem> Items { get; set; }
}
However further down I might want to have something like this:
<button class="btn btn-default" #onclick="#(() => EditObject(item.Id))">Edit</button>
protected void EditObject(int id)
{
TItem cust = _itemServices.Details(id);
}
The issue is that the above call to EditObject(item.Id) cannot resolve to a specific object at this moment because it does not know what TItem is. Is there a way to use a specific interface in the template component that each object must implement or is there another way of doing this?
The idea would be to have AddObject, EditObject, DeleteObject etc which all basically do the same thing but with different types of object.
Since you have the IList<TItem> as a parameter, the list exists at another level of the component structure outside of this component. Because of this you might be better off using the EventCallBack<T> properties for your Add, Edit, and Delete methods, and having the actual methods set as you wire the component up. This makes your template component a rendering object only, and you keep the real "work" to be done close to the actual list that needs the work done.
When you set up your template component, you might try something like this which I've had good results with.
Templator.razor
#typeparam TItem
<h3>Templator</h3>
#foreach (var item in Items)
{
#ItemTemplate(item)
<button #onclick="#(() => EditItemCallBack.InvokeAsync(item))">Edit Item</button>
}
#code {
[Parameter]
public IList<TItem> Items { get; set; }
[Parameter]
public EventCallback<TItem> EditItemCallBack { get; set; }
[Parameter]
public RenderFragment<TItem> ItemTemplate
}
Container.Razor
<h3>Container</h3>
<Templator TItem="Customer" Items="Customers" EditItemCallBack="#EditCustomer">
<ItemTemplate Context="Cust">
<div>#Cust.Name</div>
</ItemTemplate>
</Templator>
#code {
public List<Customer> Customers { get; set; }
void EditCustomer(Customer customer)
{
var customerId = customer.Id;
//Do something here to update the customer
}
}
Customer.cs
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
The key points here would be as follows:
The actual root list is living outside the templated component, as are the methods to work on that list, so all of the above are at the same level of abstraction and the same chunk of code.
The template component receives a list, a type to specify what type of the list items will be, and a method callback to execute on each item. (or series of methods, you can add the "Add" and "Delete" methods as you see fit using the same approach). It also receives the <ItemTemplate> render fragment that you specify when calling the code in the Container.razor file.
The 'foreach' in the templated item makes sure each TItem gets set up for it's own RenderFragment, set of buttons and callback functions.
Using the EventCallBack<TItem> as a parameter means that you assign a method to it that expects back the whole object of TItem. This is good, as the template now doesn't care what type the TItem is, only that is has the ability to call a method that takes a TItem as an argument! Handling the instance of whatever TItem is is now the responsibility of the calling code, and you don't have to try to constrain the generic type TItem. (Which I haven't had any luck doing in Blazor yet, maybe future releases)
As for how to render whatever TItem you feed into it, that is explained well in the documentation HERE.
Hope this helps!

How to pass html/components to a blazor template?

Here is my case:
I have a component Foo and I want it to have a blazor template called Wrapper which will be used to wrap somepart of Foo's content.
What I need to do is something like
Normal usage:
<Foo>
<Wrapper>
<div>
<p>Something in the wraper</p>
#context // context should be some content of Foo
</div>
</Wraper>
</Foo>
Inside Foo
#* Other content of Foo*#
#if(Wrapper != null){
#* Pass to Wrapper some content of Foo *#
Wrapper(#* How to render html/components here? *#)
}
#* Other content of Foo*#
But there is no way to pass html or components for the template?
How can I do this?
Your Wrapper in this case is a RenderFragment that you want to accept another RenderFragment, so it's signature would be
[Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}
Here is the complete Foo.razor
#* Other content of Foo*#
<h1>This is Foo</h1>
#if(Wrapper != null){
#* Pass to Wrapper some content of Foo *#
#Wrapper(
#<h2>This comes from Foo</h2>
)
}
<h1>There is no more Foo</h1>
#code
{
[Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}
}
Notice carefully the construct inside the call to Wrapper.
Start with #Wrapper so this is a call from Razor
The open ( after Wrapper puts you back in C# land, so -
use # to swap back to Razor code.
Now you can use Razor/HTML markup <h2>This comes from Foo</h2>
Close the call to Wrapper with a )
That is how you can use a RenderFragment that takes a RenderFragment as it's context.
The output from this would be
This is Foo
Something in the wraper
This comes from Foo
There is no more Foo
You can test it out here https://blazorfiddle.com/s/ox4tl146

Categories

Resources