Reputation: 13
`
Environment: .Net 8 Blazor WebApp Interactive render mode is Auto (Server and WebAssembly) and Interactive locations is Per page/component. Situation: I have multiple razor pages using common components (templates). I have set a number of Parameters, including select EventCallbacks. Questions:
How can I call a method in the Templated component from the Parent razor page's code?
Another related question is about accessing the Parent razor's methods from the Templated component; namely, is it possible to have an EventCallback in the template to return a value? If so, how?
I have tried Parameters and EventCallbacks. I have used the "Callback".InvokeAsync(parameter) to call a an EventCAllback method in the parent, however, I also need to return values from this InvokeAsync call.
In terms of having the Parent call a method in the child (templated component) the only approach that I have discovered is to register the component's instance with the parent and then call a method that is public in the component (which may violate best practices).
I just believe that I must be missing something; an easier and better approach to directly accessing methods in the child component. If I were building this in MAUI, then Interfaces might be the answer, however, I suspect that in .NET 8 there is a better, built in structure to handle this. I am hopeful that someone might clear this up for me.
Upvotes: 0
Views: 171
Reputation: 167
In Blazor, you can achieve communication between a parent component and a child component via different ways:
Using @ref
attribute:
In the parent Razor page:
<TemplateComponent @ref="templateRef" />
@code {
private TemplateComponent templateRef;
private void CallMethodInTemplateComponent()
{
templateRef.MethodInTemplate();
}
}
In the Templated component:
@code {
public void MethodInTemplate()
{
// Your logic here
}
}
Using Parameters and EventCallbacks:
In the parent Razor page:
<TemplateComponent ParentMethod="@ParentMethod" />
@code {
private void ParentMethod()
{
// Your logic here
}
}
In the Templated component:
@code {
[Parameter]
public Action ParentMethod { get; set; }
}
You can then invoke ParentMethod.Invoke()
in the Templated component to call the parent's method.
Returning a value from an EventCallback:
In the Templated component:
<button @onclick="CallParentMethod">Call Parent Method</button>
@code {
[Parameter]
public EventCallback<int> ParentMethod { get; set; }
private async Task CallParentMethod()
{
var result = 42; // Your value
await ParentMethod.InvokeAsync(result);
}
}
In the parent Razor page:
<TemplateComponent ParentMethod="@HandleParentMethod" />
@code {
private void HandleParentMethod(int result)
{
// Use the result here
}
}
This approach allows you to both call methods in the Templated component from the parent and return values from the Templated component to the parent using EventCallback
with a specified type
Upvotes: 0