The child component constructs a field based on a set of properties of an object that is passed to child as a parameter. In the below example, how can the child component render dynamically when any of the address fields change in the parent ? Thanks for any suggestions!
The parent component uses a child component as below and passes a parameter parentObj
.
Parent Component:
<Child ChildObj="@parentObj" />
Child component:
<div class="col-8 flex-wrap">
@Address
</div>
@code {
[Parameter]
public Person ChildObj { get; set; }
public string Address { get; set; }
protected override async Task OnInitializedAsync()
{
await Task.Run(() => {
if (ChildObj != null)
{
Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
}
});
}
}
The problem here is that OnInitializedAsync
is called only in the first time that the parameters are set in the component, you need to use OnParametersSet that will be called when:
OnParametersSetAsync or OnParametersSet are called:
- After the component is initialized in OnInitializedAsync or OnInitialized.
- When the parent component re-renders and supplies: Only known primitive immutable types of which at least one parameter has changed. Any complex-typed parameters. The framework can't know whether the values of a complex-typed parameter have mutated internally, so it treats the parameter set as changed.
<div class="col-8 flex-wrap">
@Address
</div>
@code {
[Parameter]
public Person ChildObj { get; set; }
public string Address { get; set; }
// using OnParametersSet
protected override void OnParametersSet()
{
if (ChildObj != null)
{
Address = ChildObj.Address1 + " " + ChildObj.Address2 + " " + ChildObj.City + " " + ChildObj.State + " " + ChildObj.Zip
}
}
}