Coden
Coden

Reputation: 2868

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;
}

Upvotes: 9

Views: 15793

Answers (3)

Majedur
Majedur

Reputation: 3242

In addition You can write condition like this:

style="@(!cities.Contains(rating.City) ? StyleForRow(rating.City,rating.Citywide):string.Empty)"

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273169

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.

Upvotes: 14

Bennyboy1973
Bennyboy1973

Reputation: 4208

You can put variables almost anywhere in your markup, very much including style or class attributes:

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

@code {
    int MyNumber { get; set; }
}

Upvotes: 1

Related Questions