Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ensure new instances of a Blazor components are created

I’m seeing some odd behaviour with Blazor with event hooks and the firstRender argument of OnAfterRender.

My parent component creates a dynamic set of child components:

Parent:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@if (_childObjects != null)
{
    @foreach (var childObject in _childObjects )
    {
        <ChildComponent ChildObject=@childObject />
     }
 }     

Child:

[Parameter]
public ChildObject ChildObject { get; set;  }

What happens is on clicking certain buttons that parent re-renders with a new set of child objects. I expect it to create new instances of ChildComponent for that, which it partially does.

But somehow when it hits this code:

protected override void OnAfterRender(bool firstRender)

… at this point, the value of firstRender is false and everything seems to be already initialised as per the previous render of the parent.

>Solution :

I expect it to create new instances of ChildComponent

Why? Blazor sees a (Child) Component with a different parameter.

You can help the differ by adding @key, I think that will do what you want:

@foreach (var childObject in _childObjects )
{
    <ChildComponent @key="childObject" ChildObject="childObject" />
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading