Blazor - Passing a function to dynamic component

2.8k views Asked by At

I'd like to have a fluent communication between components via DynamicComponent in Blazor. Thus I'd like to know whether its possible to pass a function to a DynamicComponent since now it doesn't know that the would be rendered components need a function to fully operate. All suggestions are welcome.

Index.razor

@page "/"

/*This is where I'd like for all of my components to get rendered cleanly*/
<DynamicComponent Type="selectedType" /*Here I'd like to pass a function "GoToComponent"*/ />

@code {
    public void GoToComponent(string name)
    {
        selectedType = Type.GetType($"Namespace.Pages.{name}");
    }
}

LandingComponent.razor

<p @onclick="() => OnClickFunction.InvokeAsync("First")">GO TO FIRST</p>
<p @onclick="() => OnClickFunction.InvokeAsync("Second")">GO TO SECOND</p>

@code {
    [Parameter] public EventCallback<string> OnClickFunction { get; set; }
}

FirstComponent.razor

<p @onclick="() => OnClickFunction.InvokeAsync("Landing")">GO TO LANDING</p>
<p @onclick="() => OnClickFunction.InvokeAsync("Second")">GO TO SECOND</p>

@code {
    [Parameter] public EventCallback<string> OnClickFunction { get; set; }
}

SecondComponent.razor

<p @onclick="() => OnClickFunction.InvokeAsync("First")">GO TO FIRST</p>
<p @onclick="() => OnClickFunction.InvokeAsync("Landing")">GO TO LANDING</p>

@code {
    [Parameter] public EventCallback<string> OnClickFunction { get; set; }
}
1

There are 1 answers

2
MrC aka Shaun Curtis On BEST ANSWER

Here's a revised Landing.razor. First and Second should be similar.

<p @onclick="() => OnClick(typeof(First))">GO TO FIRST</p>
<p @onclick="() => OnClick(typeof(Second))">GO TO SECOND</p>

@code {
    [Parameter] public EventCallback<Type> OnClickFunction { get; set; }

    private void OnClick(Type type)
    {
        OnClickFunction.InvokeAsync(type);
    }
}

And Index:

@page "/"
<DynamicComponent Type=this.selectedType Parameters=this.parameters/>

@code {
    private Type selectedType = typeof(Landing);

    private Dictionary<string, object> parameters => new Dictionary<string, object>()
    {
        { "OnClickFunction", EventCallback.Factory.Create<Type>(this, GoToComponent)}
    };

    public void GoToComponent(Type type)
    {
        this.selectedType = type;
        this.StateHasChanged();
    }
}