Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the target element on click event in Blazor

I want the exact target on which the click event has been triggered in ASP.NET Core blazor. Is this achievable?

like image 944
Prem Kumar Avatar asked Dec 06 '19 12:12

Prem Kumar


People also ask

How do you use onclick in Blazor?

Adding a button onclick event The first thing we need to is to create a NewComment property. This will store the textarea value. We then need to bind our NewComment property to the textarea value. We do that by using the @bind attribute.


2 Answers

You can use @ref to get a reference to a DOM object, then pass it as a parameter to your handler function.

You can then pass it as a parameter to the JS Interop.

For example:

Counter.razor

@page "/counter"
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<p>Last button clicked: @lastButtonClicked</p>

<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button2))">Click me</button>


@code {

    private ElementReference button1;
    private ElementReference button2;

    private int currentCount = 0;
    private string lastButtonClicked = "None";

    private async void IncrementCount(ElementReference element)
    {
        currentCount++;
        await JSRuntime.InvokeVoidAsync("setElementText", element, "I was clicked");
    }
}

And make sure to add this script to Index.html

<script>
    window.setElementText = (element, text) => { console.log(element); element.innerText = text; }
</script>

Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.1#detect-when-a-blazor-app-is-prerendering

like image 81
Gabriel Cappelli Avatar answered Sep 21 '22 13:09

Gabriel Cappelli


In .razor file:

@for (int i = 0; i < 1000; i++)
{
    int j = i;
    <input type="text" @onchange='eventargs => HandleValueChange(eventargs, "my first textbox from row " + j.ToString())' />
    <input type="text" @onchange='eventargs => HandleValueChange(eventargs, "my second textbox from row " + j.ToString())' />
}

@code {
    protected void HandleValueChange(ChangeEventArgs evt, string elementID)
    {

    }
}

Note: The key here is the int j = i declaration in the inner-loop scope ... if you pass i to the event handler you will always get '1000' i.e. it's final value from the outer loop scope

like image 30
Leon Avatar answered Sep 20 '22 13:09

Leon