americanslon
americanslon

Reputation: 4298

Update variable in the layout from component - Blazor

I have layout defined as such

@layout MainLayout

@inherits LayoutComponentBase

<CascadingValue Value="this">
    @Body

    @("_total " + _total)

    @("_perPage " + _perPage)

</CascadingValue>

@code {
    public int _total;
    public int _perPage;
}

Then in component receive the layout reference

[CascadingParameter] public Layout Layout { get; set; }

And the set it as such in

protected override async Task OnInitializedAsync()
    {
    Layout._total = 3;
    Layout._perPage = 3;
}

Problem is the values in the Layout don't get updated. I tried with 'StateHasChanged` after the setter statements but that doesn't seem to make a difference

Upvotes: 0

Views: 2511

Answers (2)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30485

You are setting the value, but there's nothing driving a StateHasChanged event in the Layout component. You can:

  1. Add a method to the Layout to explicitly call StateHasChanged which you call from your component.
  2. Make your values properties and add setters that call StateHasChanged - can get messy!.
  3. Add a specific method to set the values and call StateHasChanged as detailed in Surinder's answer.

Upvotes: 0

Surinder Singh
Surinder Singh

Reputation: 1468

Have public function to set values in your layout component like this

@layout MainLayout

@inherits LayoutComponentBase

<CascadingValue Value="this">
    @Body

    @("_total " + _total)

    @("_perPage " + _perPage)

</CascadingValue>

@code {
    public int _total;
    public int _perPage;
    
    public void SetTotal(int tot)
    {
        _total = tot;
        StateHasChanged();
    }

     public void SetPerPage(int num)
    {
        _perPage= num;
        StateHasChanged();
    }
}

Use your Layout component anywhere like this, its important to use OnAfterRender instead of OnInitialized, as OnAfterRender is called once all html is mounted in components

<Layout @ref=layout></Layout>

private Layout layout;

protected override void OnAfterRender(bool firstRender)
{
    if (firstRender)
    {
        layout.SetTotal(3);
        layout.SetPerPage(3);
    }
}

Upvotes: 1

Related Questions