Reputation: 6842
Newbie question and maybe this is a consequence of doing so much client-side development, but why do I generally not see elements assigned an Id value?
Upvotes: 8
Views: 7164
Reputation: 350
I had a need to refer to an element within a custom component from another element within that same component. If you hard code the id of the item, you can get duplicate ids because the custom component could be rendered multiple times on the same page.
I solved this problem by adding an Id parameter that I internally initialize to the value of a guid:
[Parameter] public string Id { get; set; } = Guid.NewGuid().ToString("N");
The "N" format specifier is important to ensure the id generated doesn't contain illegal characters.
I then was able to prefix/suffix any internal elements with this value to guarantee a unique element id:
<datalist id="datalist_@Id">
@for (int i = 0; i < Values.Count; i++)
{
<option>@i</option>
}
</datalist>
I made the Id property a parameter so that I could assign a more meaningful id in a parent component if I wanted. The child component has everything wrapped in a div so that the id is also referenceable directly, if necessary:
<div id="@Id">
@if (Values != null)
{
<input type="range"
class="w-100"
min="0" max="@(Values.Count - 1)"
value="@SelectedValueIndex"
@oninput="SliderOnInput"
list="datalist_@Id"
/>
<datalist id="datalist_@Id">
@for (int i = 0; i < Values.Count; i++)
{
<option>@i</option>
}
</datalist>
}
</div>
Upvotes: 1
Reputation: 7117
Blazor components are just placeholders for stuff that is rendered to the DOM.
Assigning ids to them won't help because you won't find e.g. a <counter>
element once the page has been rendered.
However, you can, of course, assign ids to the HTML elements which are rendered by your component.
e.g the component can look like this
<h1 id="myCounter">Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
Upvotes: 8