Search code examples
blazorwebassemblyblazor-webassembly

Blazor: How to conditionally style an element


In Blazor i do want to style the input element with a condition. Here the code what I do use now, it works but later I faced a problem because here three different input elements are used.

@if (MyNumber > 100) 
    { <input type="number" @bind=MyNumber @bind:event="oninput" /> }
else if (MyNumber < 1)
    { <input type="number" @bind=MyNumber @bind:event="oninput" style="color:red" /> }
else
    { <input type="number" @bind=MyNumber @bind:event="oninput" style="background:lightgreen" /> }

Is there a better possibility to set the style with a condition?

Edit: Thanks for the answers, there are definately several solutions possible. I even found another one using the attributes:

<input type="number" @bind=MyNumber @bind:event="oninput" @attributes="SetStyle(MyNumber)" />
@code{
public Dictionary<string, object> SetStyle(int myNumber)
{
    var dict = new Dictionary<string, object>();
    if (myNumber > 100) { }
    else if (myNumber < 1) dict.Add("style", "color:red");
    else dict.Add("style", "background:lightgreen");
    return dict;
}

Solution

  • There are many ways to do it, I would use:

    <input style="@StyleForNumber(MyNumber)" type="number" @bind=MyNumber @bind:event="oninput" />
    

    ...

    private string StyleForNumber(int n)
    {
       if (n > 100) return "";
       if (n < 1)  return "color:red";
       return "background:lightgreen";
    }
    

    the function can be re-used and easily maintained.

    I would probably use Css classes instead of direct styles though.