Bryan Dellinger
Bryan Dellinger

Reputation: 5294

binding button to child component blazor

here is my fiddle https://blazorfiddle.com/s/d15hrars

I have a select component that changes the class of a table. there is also a button that can set the selected value of the select component. but pressing the button does not update the selected value in the drop down (the select component)

so pressing the button highlights the row San Jose but does not update the drop down. not sure why

parent component

@page "/"

  <table class="table table-sm table-bordered table-striped">
    <thead>
        <tr>
            <th>City</th>
        </tr>
    </thead>
    <tbody>
  @foreach (string c in Cities)
        {
            <tr class="@GetClass(c)">
                <td>@c</td>
            </tr>
        }
    </tbody>
    </table>

<SelectFilter values="@Cities"
              title="@SelectTitle"
              @bind-SelectedValue="SelectedCity"/>

<button class="btn btn-primary"
        @onclick="@(() => SelectedCity = "San Jose")">
    Change
</button>

@functions {
    string[] Cities = new string[] { "New York", "Los Angeles", "Denver", "San Jose" };

    public string SelectedCity { get; set; }

    public string GetClass(string city) =>
        SelectedCity == city ? "bg-info text-white" : "";

     [Parameter]
    public string SelectTitle { get; set; }
    
}

child component

<div class="form-group">
    <label for="select-@Title">@Title</label>
    <select name="select-@Title"
            class="form-control"
           @onchange="HandleSelect"
            value="@SelectedValue"
            @attributes="Attrs">
        <option disabled selected>Select @Title</option>
        @foreach (string val in Values)
        {
            <option value="@val" selected="@(val == SelectedValue)">@val</option>
        }
    </select>
</div>

@code {
    [Parameter]
    public IEnumerable<string> Values { get; set; } = Enumerable.Empty<string>();

    public string SelectedValue { get; set; }
    [Parameter]

    public string Title { get; set; } = "Placeholder";

    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> Attrs { get; set; }

    [Parameter]
    public EventCallback<string> SelectedValueChanged { get; set; }

    public async Task HandleSelect(ChangeEventArgs e)
    {
        SelectedValue = e.Value as string;
        await SelectedValueChanged.InvokeAsync(SelectedValue);
    }
}

Upvotes: 0

Views: 226

Answers (1)

Brian Parker
Brian Parker

Reputation: 14523

Your child component is missing a Parameter attribute.

    [Parameter]
    public string SelectedValue { get; set; }

Upvotes: 2

Related Questions