Reputation: 581
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
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.
// 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>
}
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);
}
}
}
@if (Customer != null)
{
<p>@Customer.CustomerName</p>
<p>@Customer.AgencyName</p>
}
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?
}
}
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?
Upvotes: 1
Views: 8623
Reputation: 4256
I recommend going through https://blazor-university.com. It's the site that kind of got me kick-started when I first started with Blazor.
In regard to your question, I recommend the following:
https://blazor-university.com/components/component-lifecycles/
In particular, the following statement should prove useful in your case (from that link):
OnInitialized / OnInitializedAsync
This method is only executed once when the component is first created. If the parent changes the component’s parameters at a later time, this method is skipped.
It seems likely that simply changing which method you override will solve your problem, since OnParametersSetAsync
behaves as you've described, and 'OnInitializedAsync' behaves as you want. :D
Upvotes: 2