I'm new to Blazor and I'm currently working on a Blazor Webassembly .net 5.0 application.
I try to figure out the correct way to
- render a child component
- from a parent component
- on button click (form submit)
- pass parameters from the parent component to => the child component
My current solution seems to work, but unfortunately it ends in an infinite rendering loop: I use the OnParametersSetAsync
method in the child component to handle the data loading.
Side note: I use Telerik Blazor components, but it should have no impact.
- My parent component looks like this:
- View (parent)
// I want to submit a form to set a bool = true, and then to rend the child component - is that ok?
<EditForm OnValidSubmit="@(async () => await StartEverything())">
<label for="OrderNumber">OrderNumber: </label>
<TelerikTextBox @bind-Value="OrderNumber" Id="OrderNumber" />
<TelerikButton ButtonType="@ButtonType.Submit">Start Everything</TelerikButton>
</EditForm>
@if (ShowChild)
{
<MyChildComponent OrderNumber="OrderNumber"/>
}
else
{
<div>Please enter an order number.</div>
}
- Code Behind (parent)
public class MyParentComponent : ComponentBase {
protected int OrderNumber { get; set; }
protected bool ShowChild { get; set; }
protected async Task StartEverything()
{
if (OrderNumber > 0)
{
await Task.FromResult(ShowChild = true);
}
}
}
- My child component looks like this:
- View (child)
@if (Customer != null)
{
<p>@Customer.CustomerName</p>
<p>@Customer.AgencyName</p>
}
- Code Behind (child)
public class MyChildComponent : ComponentBase {
// I need this Parameter sent from my parent component
[Parameter]
public int OrderNumber { get; set; }
protected CustomerViewModel Customer { get; set; }
protected override async Task OnParametersSetAsync()
{
var parameterForQuery = OrderNumber; // this should hold the value sent from the parent component
// Load Customer ViewModel Data here - is this the correct event? What is the best approach?
}
}
- Item ViewModel
public class CustomerViewModel
{
public string CustomerName { get; set; }
public string AgencyName { get; set; }
}
Do you know how to correctly render a Child Component within a Parent Component and pass parameters from the Parent Component to the child component - then render the child component ONLY ON BUTTON CLICK (form submit, no infinite render loop)?
Do you know how to solve this problem?