Describe the bug
MatTab's default tab is always set to the first one (zero) regardless of the value binded to ActiveIndex. This issue is also present in the TabIndex example from the MatBlazor docs.
To Reproduce
Create the below component and run
<MatButton` OnClick="@ChangeTab">Change Tab</MatButton>
<div>
Active tab index: @tabIndex
</div>
<MatTabGroup @bind-ActiveIndex="@tabIndex">
<MatTab Label="First">
First Content
</MatTab>
<MatTab Label="Second">
Second Content
</MatTab>
<MatTab Label="Third">
Third Content
</MatTab>
<MatTab Label="Fourth">
Fourth Content
</MatTab>
</MatTabGroup>
@Code {
public int tabIndex = 2; //notice that this is set to 2. In the docs, it is set to zero
//what I expect is the active tab on initialization to be the third one
void ChangeTab(MouseEventArgs e)
{
tabIndex = tabIndex < 3 ? tabIndex + 1 : 0;
}
}
Expected behavior
I expect the active tab to be set to the tabIndex on initialization
Additional context
I need this to work to be able to "remember" the user's last clicked tab.
Try calling StateHasChanged();
I dynamically set active tab (though not through a button click) and it doesn't work without StateHasChanged();
@americanslon Oh my God, thank you so much. It works. I completely forgot about the StateHasChanged() method.
Where exactly do you need to put the StateHasChanged() method? I've tried putting it inside OnInitializedAsync, din't work.
Call it in OnAfterRender().
It seems you can only change the tabIndex after the tabs have loaded. So do that in OnAfterRender() and call StateHasChanged().
Most helpful comment
@americanslon Oh my God, thank you so much. It works. I completely forgot about the
StateHasChanged()method.