Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass element as parameter to function

Is there any way to pass an element as a parameter to the onclick (or any other) function, without defining a ref variable ?

Something like you would do in Angular for example <button #myBtn (click)='foo(myBtn)'>

The current way that I know how to achieve this in Blazor is a bit verbose.

<button @ref=MyButton @onclick='(()=>foo(MyButton))'>

@code{
 ElementReference MyButton;
}

I would like to get rid of the @code part if that is possible.

like image 886
Bogdan B Avatar asked Sep 07 '25 06:09

Bogdan B


1 Answers

If you need to do some JsInterop stuff, then you don't need @ref.

<button id="mybutton" @onclick='(()=>Foo("mybutton"))'>

on your Foo method:

        async Task Foo(string id)
        {
        //...do something before
        await JsRuntime.InvokeVoidAsync("doSomething ", id);
        //...do something after js function invoked
        }

on your Js:

doSomething = (id) => {
    var element = document.getElementById(id);
    // do something...
}
like image 103
The Backer Avatar answered Sep 09 '25 20:09

The Backer