Live Chat Icon For mobile
Live Chat Icon

How do I get two-way binding in Blazor with the Select component?

Platform: Blazor| Category : General, Components, Data binding

To use two-way binding in a Blazor component, add the bind attribute to a field. Two-way data binding pushes the changes to the component, gets the data from the component end, and updates its own data accordingly.

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;

}

Refer to this link for more details.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.