Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop event propagation in Blazor Server app

I'm using Grid.Blazor library to render server side grid on Blazor app. One of the column has a button with click event. So when button is clicked then grid row event is also fired along with button click event. I want to stop event propagation and only let button click event fired.

Grid:

  <GridComponent @ref="_gridComponent" T="QuickLists" Grid="@_grid"  OnRowClicked="@(async (item) => await ExerciseDetails(item))"></GridComponent>


Action<IGridColumnCollection<QuickExcerciseLists>> columns = c =>
        {
            c.Add().Titled("Actions").RenderComponentAs(typeof(ChildComponent)).SetWidth("5%");
            c.Add(o => o.Name, comparer).Titled("Name").SetWidth("10%");
            c.Add(o => o.Age, comparer).Titled("Age").SetWidth("15%");
            c.Add(o => o.Address, comparer).Titled("Address").RenderComponentAs<MatTooltip>().SetWidth("15%");
        };

Custom Column Component :

<MatBlazor.MatButton Icon="@MatIconNames.Remove_red_eye" @onclick="@ShowData" @onclick:stopPropagation="true"></MatBlazor.MatButton>

I tried passing @onclick:stopPropagation in the child button component. But it's given below compile error.

The component parameter 'onclick' is used two or more times for this component. Parameters must be unique (case-insensitive). The component parameter 'onclick' is generated by the '@onclick:stopPropagation' directive attribute.

I'm running .Net core 3.1.201. Any help is highly appreciated.

like image 259
Venky Avatar asked May 03 '20 18:05

Venky


People also ask

How do you stop event propagation?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

What is EventCallback Blazor?

The EventCallback<T> class is a special Blazor class that can be exposed as a Parameter so that components can easily notify consumers when something of interest has occurred.

How do you get the target element onclick event in Blazor?

Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop.


1 Answers

In case it helps, and to add to the comment @Ivan made for the MatBlazor MatButton/MatIconButton which didn't seem to work for me, I used the following workaround:

<div @onclick:stopPropagation="true" @onclick:preventDefault="true">
  <MatButton OnClick="@DoSomething" @ref="MyButton">Do it!</MatButton>
</div>

I needed to use both stopPropagation and preventDefault. I had to use the div wrapper as MatButton didn't allow me to add multiple onclicks.

like image 68
pfeds Avatar answered Nov 08 '22 07:11

pfeds