Blazor - Get Started with RepeatButton

Blazor - Get Started with Smart.RepeatButton

Setup The Project

Follow the Getting Started guide to set up your Blazor Application with Smart UI.

Setup Basic RepeatButton

Smart.RepeatButton is a button element that repeats a single action until release.

  1. Add the RepeatButton component to the Pages/Index.razor file
    <RepeatButton></RepeatButton>
  2. Delay indicates the time in miliseconds between the execution of each action, while InitialDelay applies delay only on the very first Click event:
    <RepeatButton Delay="100">Repeat Button</RepeatButton>
  3. Optionally, set the name and value of the RepeatButton:
    <RepeatButton Delay="100" Name="repeat" Value="enabled">Repeat Button</RepeatButton>
Basic RepeatButton

RepeatButton Event

In order to atach a change listener to the RepeatButton, it is necessary to use the IJSRuntime interface

@inject IJSRuntime JS

Create an Increase function that will increment a number by one every time it is called:

public static int number = 1;

[JSInvokable]
public void Increase()
{
  number++;
  StateHasChanged();
}

Using JSInterop, inoke a custom JS function called "setListener":

protected override void OnInitialized()
{
    base.OnInitialized();
    JS.InvokeVoidAsync("setListener", DotNetObjectReference.Create(this), nameof(Increase));
}

Inside the \_Host.cshtml file (server-side Blazor) or wwwroot/index.html (client-side WebAssembly Blazor), create a function that will attach an event listener to the DOM element and will then call our C# function:

<script>
  (function (global) {
      global.setListener = (dotNetHelper) => {
          setTimeout(function(){
              document.querySelector("smart-repeat-button").addEventListener('click', function(){
                  dotNetHelper.invokeMethodAsync('Increase')
              })
          }, 0)
      }  
  })(window); 
</script>

The demo below will increase the counter, while the user is pressing the RepeatButton:

<RepeatButton Delay="100" id="increase-btn">+</RepeatButton>
<h3>@number</h3>
@code{
    public static int number = 1;

    [JSInvokable]
    public void Increase()
    {
        number++;
        StateHasChanged();
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        JS.InvokeVoidAsync("setListener", DotNetObjectReference.Create(this), nameof(Increase));
    }
}
      
RepeatButton event