Reputation: 934
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.
Upvotes: 4
Views: 3228
Reputation: 718
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...
}
Upvotes: 2
Reputation: 54
You can pass refence like that but it should filled or try to pass cascading parameter . It can reachable on parent to child .
You can create .cs file and inherit it from ComponentBase and also on component page you should inherit that base.
Example ComponentClass: public class TextBoxComponentBase: ComponentBase
Example Component: @inherits TextBoxComponentBase
You will get rid of @code part like this .
Upvotes: 0