5

I have the following code.

<input id="search" type="text" @bind="Search" @onkeypress="SearchChanged" />
@code {
    string Search;

    void SearchChanged() 
    { 
        var s = Search; // Search is always one character behind
    }
}

Typing in the text box will trigger the function SearchChanged. However, the value it got is always one character before the typed text. For example, setting a break point in SearchChanged,

Typed Value of  Search
===== ================
a     null
ab    a
abc   ab
abcd  abc

BTW, the @onkeypress doesn't work in Internet Browser?


Tried to change the code to

<input id="search" type="text" @bind="Search" />
@code {
    string search;
    string Search 
    {
        get { return search; }
        set {
            search = value;
            ResultList = GetNewList(search).Result.ToList(); 
        }
    }

    void SearchChanged() 
    { 
        var s = Search; // Search is always one character behind
    }
}

I set a break point in the set { }, however, the break point is hit just one or two times when typing the text box?

ca9163d9
  • 27,283
  • 64
  • 210
  • 413

1 Answers1

3

You are looking for @bind-value:event:

<input id="search" 
       type="text" 
       @bind-value="Search" 
       @bind-value:event="oninput"
/>

@code {
  string search;
  string Search 
  {
    get { return search; }
    set {
        search = value;
        ResultList = GetNewList(search).Result.ToList(); 
      }
  }

Quoting Data Binding docs:

In addition to handling onchange events with @bind syntax, a property or field can be bound using other events by specifying an @bind-value attribute with an event parameter (@bind-value:event).

dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • I want to use Rx to throttle the key press so less database calls will be invoked. Is there a way to to create IObservable on the events for Blazor? – ca9163d9 Oct 14 '19 at 22:12
  • This is a new question. But I already answered here: https://stackoverflow.com/a/57545940/842935 – dani herrera Oct 15 '19 at 06:00