I want to add an HTML5 data-attribute to my blazor component:
<div data-is-loaded=@_isLoaded>
...
</div>
@code {
private bool _isLoaded = false;
protected override void OnInitialized() => _isLoaded = true;
}
But that renders: <div data-is-loaded="">
.
I also tried:
- splatting to a dynamically created dictionary
<div @attributes=@(new Dictionary<string, object> { { "data-is-loaded", _isLoaded } })>
- and using a property instead of a field
...with the same result.
I know the variable contains the value I expect, because this does work:
<div class=@(_isLoaded ? "loaded" : "")>
As you can see, this is not data passed into the component. It's just some basic value I want to add as a data-attribute (which as I'm sure you've guessed, is a way to signal something to the component's associated javascript).
How can this be done?
CodePudding user response:
HTML attributes must be strings, so the issue can be solved by converting _isLoaded
to a string:
<div data-is-loaded=@(_isLoaded ? "true" : "false")>
...
</div>
@code {
private bool _isLoaded = false;
protected override void OnInitialized() => _isLoaded = true;
}
You can change the strings to fit what you need.
Here is the example on blazorfiddle (you may need to use chrome): https://blazorfiddle.com/s/mj2vt94g