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