In the following example, we created a Select component and implemented two-way binding to the parent component.
Create a Select component in the Pages folder.
[SelectComponent.razor]
<div>
<select id="Item" class="form-control-sm" @bind="@ListItem">
@foreach (var list in SelectList)
{
@if (ListItem != null && String.Equals(list, ListItem, StringComparison.OrdinalIgnoreCase))
{
<option selected value="@list">@list</option>
}
else
{
<option value="@list">@list</option>
}
}
</select>
</div>
@code {
public IEnumerable<string> SelectList = new List<string>()
{
"List 1",
"List 2",
"List 3",
"List 4",
"List 5"
};
private string listItem { get; set; }
[Parameter]
public string ListItem
{
get { return listItem; }
set {
if (listItem != value)
{
listItem = value;
if (ListItemChanged.HasDelegate)
{
ListItemChanged.InvokeAsync(value);
}
}
}
}
[Parameter]
public EventCallback<string> ListItemChanged { get; set; }
}
Now define the Select component to in the Index.razor page and implement the two-way binding using the @bind attribute.
[Index.razor]
@page "/"
<div>
<label>Bind Value</label>
<input type="text" @bind="@Content" @bind:event="oninput" />
<p>@Content</p>
</div>
<div>
<SelectComponent @bind-ListItem="@Content" />
</div>
@code {
[Parameter]
public string Content { get; set; } = string.Empty;
}