WingiM
WingiM

Reputation: 117

Blazor - Refresh child component on its parameter change

I have a blazor page that uses my custom ExamTicketDisplay component with TicketId parameter like this <ExamTicketDisplay TicketId="@_currentTicket"/>

As _currentTicket's value changes I expect ExamTicketDisplay to be re-rendered with its new parameter value, but that does not happen. The component does not re-render with new value, OnInitializedAsync method is not called even if parent's StateHasChanged() is called.

How can I make this child component to re-render when the parameter changes?

I tried to call OnInitializedAsync method manually in parameter's set method, but that looks like a crunch for me

[Required]
[Parameter]
public int TicketId
{
    get => _ticketId;
    set
    {
        _ticketId = value;
        OnInitializedAsync();
    }
}

Upvotes: 2

Views: 3037

Answers (1)

Dimitris Maragkos
Dimitris Maragkos

Reputation: 11392

You are not supposed to manually call OnInitializedAsync like that. For this you need to use OnParametersSetAsync lifecycle method.

[Required]
[Parameter]
public int TicketId { get; set; }

private int _currentTicketId;

protected override Task OnParametersSetAsync()
{
    if (_currentTicketId != TicketId)
    {
        _currentTicketId = TicketId;
        // ticket id has changed, do something
    }
}

Upvotes: 6

Related Questions