Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass function as parameter to dynamically created component blazor

I am trying to pass some parameters to a dynamically generated component

Parent

...
    DynamicComponent = builder =>
        {
            Type moduleType = Type.GetType(ChildComponentName);
            System.Diagnostics.Debug.WriteLine(moduleType);
            if (moduleType != null)
            {
                builder.OpenComponent(0, moduleType);
                builder.AddAttribute(1, "title", "Delete + " + item.Name + "?");
                builder.AddAttribute(2, "content", "Are you sure you want to delete this organization?");
                builder.AddAttribute(3, "YesCallback", whatgoeshere?);
                builder.AddComponentReferenceCapture(1, inst => { child = Convert.ChangeType(inst, moduleType); });
                builder.CloseComponent();
            }
        };

    public void Delete(string msg)
        {
            System.Diagnostics.Debug.WriteLine(msg);
            items.RemoveAt(DeleteIndex);
        }
...

Child

...
    [Parameter] public string Title { get; set; }
    [Parameter] public string Content { get; set; }
    [Parameter] public EventCallback<string> YesCallback { get; set; }
...

The component get's generated and displayed fine. The first two parameter are set fine. What I can't figure out is how to pass the parent Delete function as third attribute so the child can call it.

like image 580
americanslon Avatar asked Mar 26 '26 04:03

americanslon


1 Answers

You can use the EventCallbackFactory.Create to create event callbacks from simple actions. Along with the action you have to pass the event receiver which is usually the component on which the action is being executed.

You can access the factory through EventCallback.Factory:

var callback = EventCallback.Factory.Create<string>(this, arg =>
{
    // do something
});

You can also pass a method with the correct signature instead:

var callback = EventCallback.Factory.Create<string>(this, OnCallback);

You can then pass the created event callback directly to the AddAttribute method:

builder.OpenComponent(0, componentType);
builder.AddAttribute(1, "OnSomething", callback);
builder.CloseComponent();
like image 174
poke Avatar answered Mar 28 '26 18:03

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!