Im trying to change the classes of an element inside one of my components from a page, but the classes never change. I put a Console.Writeline inside the function, and the function is definitley running.
The CircleClass variable by default is set to "danger", and that works properly, the div starts off with the danger class. The console.writeline confirms that the variable is being changed, it just isn't updating the element.
Code in component:
<div class="circle @CircleClass"></div>
@code {
private string CircleClass = "danger";
public void ChangeStatus(int status)
{
switch (status)
{
case 0:
CircleClass = "idle";
break;
case 1:
CircleClass = "safety";
break;
case 2:
CircleClass = "danger";
break;
}
Console.WriteLine($"{status} Circle: {CircleClass}");
}
}
First Attempt
@page "/"
@Inject Nav nav
<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>
In Startup.cs I added this:
services.AddSingleton<Nav>();
Second Attempt
@page "/"
<button @onclick="@(e => ChangeStatus(2))">Two</button>
private void ChangeStatus(int status)
{
Nav nav = new Nav();
nav.ChangeStatus(status);
}
I think it may have something to do with it creating a new instance of the class which isn't able to change the classes of the elements I need changing, although I believe that should be solved when using AddSingleton.
Anyone know what could be causing this issue?
Calling the function inside of the component confirms that the function actually works.
Component:
protected override void OnInitialized()
{
ChangeStatus(1);
}
What I am trying:
Nav.razor
<li id="status">
<div class="circle @CircleClass"></div>
</li>
@code {
private string CircleClass = "danger";
public void ChangeStatus(int status)
{
switch (status)
{
case 0:
CircleClass = "idle";
break;
case 1:
CircleClass = "safety";
break;
case 2:
CircleClass = "danger";
break;
default:
CircleClass = "idle";
break;
}
Console.WriteLine($"{status} Circle: {CircleClass}");
InvokeAsync(() =>
{
StateHasChanged();
});
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<Nav>();
}
Index.razor
@page "/"
@inject Nav nav
<button @onclick="@(e => nav.ChangeStatus(0))">Zero</button>
<button @onclick="@(e => nav.ChangeStatus(1))">One</button>
<button @onclick="@(e => nav.ChangeStatus(2))">Two</button>
In my code examples above, I am using buttons to try to run functions in the nav component from a page, but eventually I am going to run these functions from different places that wont be pages without direct user input.
The Nav component is defined/created in my MainLayout, it isn't directly applied to the Index page.
