'In Blazor, how to set element IDs to different values per component instance, but the same value within the component instance?
In Blazor, I might often have the same component render on a page twice. Inside this component, I might have <label for="foo">
that refers to an <input id="foo">
in the same component.
Is there a convenient way to set the two IDs to different values per component, but the same value within the component? If each component had a parameter that was different, we could use that, but what about in the case where there is no difference between the parameters' values?
I think I'd have to declare a private instance value, say private Guid ComponentInstanceId {get;} = Guid.NewGuid();
and use that with <label for="foo-@ComponentInstanceId">
...<input id="foo-@ComponentInstanceId">
, but maybe there's a better way?
Solution 1:[1]
Instead of using <input>
directly, I typically have my own custom input components (MyDate
, MySelect
etc). And I use GetHashCode() of the component instance for this, here's partial code for MySelect.razor
:
<label for="@this.GetHashCode()">@Label</label>
<select id="@this.GetHashCode()" @bind=Value>
...
</select>
And then I invoke them without worrying about id:
<MySelect Label="Source of Change" @bind-Value=ChangeOrder.SourceOfChange />
It seems to be reliable so far, with every component on the page having unique id, but it's technically not guaranteed unique by .net for all cases. You may want to provide your own GetHashCode or other function, e.g. based on position in the document tree.
...Or simply use Guid.NewGuid() but use the same guid in both label and input.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ekus |