0xBADF00
0xBADF00

Reputation: 1120

RazorComponent in Blazor included several times in the same page shares code

I have a RazorComponent called "MyComponent" that I have included in another RazorComponent described in below code.

@foreach (var MyComponentConfig in MyComponentsConfig.GetChildren())
{
    <MyComponent Session="@GetSessionService(MyComponentConfig.Key)"></MyComponent>
}

I thought that this would create a separate instance of MyComponent on each iteration of the loop, but it seems that the code is somehow shared. The "OnInitialize" function is only called once in MyComponent, even do I have 5 iteration in the loop. How can I make it, so that a separate instance of MyComponent is created instead of a shared instance?

Upvotes: 0

Views: 43

Answers (1)

enet
enet

Reputation: 45626

I thought that this would create a separate instance of MyComponent on each iteration of the loop, but it seems that the code is somehow shared. The "OnInitialize" function is only called once in MyComponent, even do I have 5 iteration in the loop.

You are wrong. Try this code:

MyComponent.cs

<h3>MyComponent</h3>

@code {        
    protected override void OnInitialized()
    {
        Console.WriteLine("OnInitialized: {0}", ID.ToString());
    }

    [Parameter]
    public int ID { get; set; }

}

Parent

@page "/"

@for( var count = 1; count < 5; count++)
{
    <MyComponent ID="@count"/>
}

@code
{
    protected override void OnInitialized()
    {
        Console.WriteLine("Parent component initialized");
    }
}

Result:

Parent component initialized

OnInitialized: 1

OnInitialized: 2

OnInitialized: 3

OnInitialized: 4

Note: It would be a good idea to attach the the @key directive attribute to the MyComponent component, like this

<MyComponent @key="MyComponentConfig" Session="@GetSessionService(MyComponentConfig.Key)"></MyComponent>

You can assign whatever value you want to the @key directive as long as it is unique. In my code sample you would do it like this:

<MyComponent  @key="@count" ID="@count"/>

Read more here

Upvotes: 1

Related Questions