Search code examples
c#.net-coreblazorblazor-server-sideblazor-client-side

Blazor “@ref” refers to the last element in loop command


The “@ref” refers to the current element that is correct.

“@ref” refers to the last element in loop command that is not correct (in my example, the last tr element of the table element).

I want that “@ref” refers to per element individually (in my example, per tr element of the table element) not to the last element.

@inject IJSRuntime JsRuntime;

<table class="table">
    <tbody>
        @foreach (var item in Items)
        {
            <tr @ref="@row" @onclick="() => {Rowclick(row);}">
                <td>@item</td>
            </tr>
        }
    </tbody>
</table>

@code
{
    public string[] Items = new string[] { "Tomas", "Jack", "Michael" };

    public async void Rowclick(ElementReference row)
    {
        await JsRuntime.InvokeAsync<object>("updateBackgroundColor", row);
    }
}

//--------------------------

<script type="text/javascript">
    function updateBackgroundColor(row) {
        row.bgColor = 'red';
    }
</script>

Solution

  • This is your answer:

        @using Microsoft.AspNetCore.Components;
        @inject IJSRuntime JsRuntime;
    
        <table class="table">
        <tbody>
            @foreach (var item in Items)
            {
                <tr @ref:suppressField @ref="@item.Row" @onclick="@(() => {ClickForTestRow(item.Row);})">
                    <td>@item.Name</td>
                </tr>
            }
        </tbody>
        </table>
    
    
    @code {
    [Parameter]
    public IList<MyModel> Items { get; set; }
    
    public async void ClickForTestRow(ElementReference row)
    {
        await JsRuntime.InvokeAsync<object>("updateBackgroundColor", row, "red");
    }
    
    public class MyModel
    {
        public ElementReference Row { get; set; }
    
        public string Name { get; set; }
    }
    }
    

    //----------------

    <script type="text/javascript">
        function updateBackgroundColor(row) {
            row.bgColor = 'red';
        }
    </script>