26

Blazor vRC1

I'm looking for a straightforward technique on how to conditionally render an attribute within an <InputText> (or any of the input components for that matter). This used to be simple in MVC Razor, where you'd just write the conditional logic within the @(...) statement. Now, writing @(...) has different meaning in the Razor syntax.

For example, I'd like to conditionally output the autofocus HTML attribute for InputText.

<InputText 
 @bind-Value="@TextProperty"
 @(MyModel.isAutoFocus ? "autofocus" : "") <-  This is invalid razor syntax!
/>
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60

4 Answers4

33

As it turns out, Blazor will not render the attribute if the value of the attribute is false or null

https://learn.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#conditional-html-element-attributes

HTML element attributes are conditionally rendered based on the .NET value. If the value is false or null, the attribute isn't rendered. If the value is true, the attribute is rendered minimized.

<InputText @bind-Value="@TextProperty" autofocus="@MyModel.isAutoFocus" />
Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60
22

This could potentially be achieved with the @attributes tag. See more here

Basically, you can add an @attributes tag to your InputText. This can bind to a parameter, or to a handy little method.

<InputText @bind-Value="@TextProperty" @attributes="HandyFunction()" />

@code{
    Dictionary<string,object> HandyFunction()
    {
        var dict = new Dictionary<string, object>();
        if(MyModel.isAutoFocus) dict.Add("autofocus",true);
        return dict;
    }
}
saniokazzz
  • 476
  • 1
  • 6
  • 21
Tom
  • 306
  • 1
  • 5
  • 1
    Thanks, although nowhere near as straightforward as it should be like in earlier editions of Razor. – Aaron Hudon Sep 20 '19 at 16:07
  • This also works if you need to conditionally set a parameter on a blazor component like if you need to pass a render fragment through. – gorrilla10101 Aug 12 '20 at 16:19
12

You could try below code:

<InputText  @bind-Value="@TextProperty"  autofocus="@(MyModel.isAutoFocus)"  />

Refer to https://github.com/aspnet/AspNetCore/issues/10122

Ryan
  • 19,118
  • 10
  • 37
  • 53
  • 3
    The presence of the autofocus attribute enables the feature. I need to conditionally write out the attribute, not the value. – Aaron Hudon Sep 20 '19 at 01:48
  • 4
    @Aaron Hudon I have tried and find that If set `autofocus= true`,it will show as `autofocus` in the input on page, if `autofocus= false`, it will not show as attribute for the input.Maybe you could open browser F12 to check the result? – Ryan Sep 20 '19 at 01:52
  • 1
    Thanks - I might just have to fall back to this, but the original question still stands, how to conditionally output an attribute. – Aaron Hudon Sep 20 '19 at 01:54
  • @Aaron Hudon I understand now but I think blazor does not support that yet.Good luck... – Ryan Sep 20 '19 at 02:30
0

Add or Remove Attributes in HTML Using Blazor

To add or remove HTML attribute via Blazor logic, I suggest you use the "attribute splatting" feature (<input @attributes=... />) built into Microsoft Blazor.

Why? Its better to modify the attributes dictionary on the element for all attributes assigned to your <input> and using the event OnInitialized(), rather than cobbling attributes inside the HTML, as the @attributes collection could have custom attributes assigned to the component in its tag helper or added elsewhere via the @attributes value on prerender events that get erased or conflict. This code below makes sure your attributes are added into the pipeline of processes for all attributes assigned to your HTML element that the @attributes feature manages.

<input @attributes="MyAttributes" />

@code {
    
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> MyAttributes { get; set; }

    protected override void OnInitialized()
    {
        // CONDITIONALLY ADD/REMOVE AN HTML ATTRIBUTE

        // Remove
        if (MyAttributes.ContainsKey("style"))
        {
            if ({Add Your Conditional Logic Here})
            {
                MyAttributes.Remove("style");
            }        
         }

         // Add
         if ({Add Your Conditional Logic Here})
         {
              var MyAttributes = new Dictionary<string, object> {{"data-helloworld", "Hello World!"}};

             // This adds your new attribute created above,
             // BUT prevents duplicates by honoring the first
             // or original attribute, if it exists.

             MyAttributes = MyAttributes.Concat(newAttribute)
            .GroupBy(i => i.Key)
            .ToDictionary(g => g.Key, g => g.First().Value);
             }
         }
     }
}

Simple Ways to Add An Attribute in Blazor

Btw...I use these techniques to force a single name-value attribute pair into HTML when modifying a Blazor component. It's not pretty, but it's all we are stuck with using their "attribute splatting" model.

This code below becomes <div style="color:blue;">Blue Text</div>:

<div @attributes="MyCSS">Blue Text</div>

@code {
    private Dictionary<string,object> MyCSS{ get; set; } = 
    new Dictionary<string,object> {{ "style","color:blue;" }};
}

If you just want to update a known attribute value in Blazor, you can also do this:

<div style="@MyCSS">Blue Text</div>

@code {
    private string MyCSS= "color:blue;";
}
Stokely
  • 12,444
  • 2
  • 35
  • 23