Home > Net >  Blazor - HTML tag inside of c# bound bool switch
Blazor - HTML tag inside of c# bound bool switch

Time:08-09

I want to add a icon into a button context depending on a bool.

How to implement a HTML tag into a c# bound bool switch?

<button type="button"> 
   @(SwitchBool? "Save" : @"<i class='\u0022'fa fa-pen'\u0022'></i>")
</button>

CodePudding user response:

You can do it like this:

<button type="button" @onclick="() => SwitchBool = !SwitchBool"> 
   @if(SwitchBool)
   {
       <text>Save</text>
   }
   else
   {
       <i ></i>
   }
</button>

@code {
    private bool SwitchBool;
}

CodePudding user response:

I don't think C# likes to have different types for the output of a ternary. But you can just build whatever string you want and cast it to MarkupString

@((MarkupString)(SwitchBool ? "Save" : "<i class='fa fa-pen'/>"))

I don't like this, though, as you really have to process the entire line to understand what it's doing. I'd rather just take the extra lines to write a conditional. Also, give your bool a meaningful name:

<button>
    @if (ReadyToSave)
    {
        <span>"Save"</span>
    }
    else 
    {
        <i class='fa fa-pen'/>
    }
</button>

The if . . . else could be crammed into a single line, but I really wouldn't suggest that.

  • Related