Blazor Textfield Oninput User Typing Delay

后端 未结 2 1672
长发绾君心
长发绾君心 2020-12-06 05:24

How can I add a delay to an event (OnInput) in Blazor ?
For example, if a user is typing in the text field and you want to wait until the user has finished typing.

相关标签:
2条回答
  • 2020-12-06 05:55

    I have created a set of Blazor components. One of which is Debounced inputs with multiple input types and much more features. Blazor.Components.Debounce.Input is available on NuGet.

    You can try it out with the demo app.

    Note: currently it is in Preview. Final version is coming with .NET 5. release

    0 讨论(0)
  • 2020-12-06 06:04

    Solution:

    There is no single solution to your question. The following code is just one approach. Take a look and adapt it to your requirements. The code resets a timer on each keyup, only last timer raises the OnUserFinish event.

    @using System.Timers;
    ...
    <input type="text" @bind-value="Data" @bind-value:event="oninput" 
           @onkeyup="@HandleKeyUp"/>
    <p>@Data2</p>
    
    @code {
        public string Data { get; set; }   
        public string Data2 { get; set; }  
        private System.Timers.Timer aTimer;
    
        protected override void OnInitialized()
        {
            aTimer = new System.Timers.Timer(1000);
            aTimer.Elapsed += OnUserFinish;
            aTimer.AutoReset = false;
        }
    
        void HandleKeyUp(KeyboardEventArgs e)
        {
            // remove previous one
            aTimer.Stop();
    
            // new timer
            aTimer.Start();        
        }    
    
        private void OnUserFinish(Object source, ElapsedEventArgs e)
        {
            InvokeAsync( () =>
              {
                Data2 = $"User has finished: {Data}";
                StateHasChanged();
              });
        }
    }
    

    Use case:

    One example of use case of this code is avoiding backend requests, because the request is not sent until user stops typing.

    Running:

    0 讨论(0)
提交回复
热议问题