简体   繁体   中英

Blazor event only works correctly while debugging

I have a component that tracks the number of words typed into a text area. The issue is that the word updates after writing the first word then stops. To make it fire off the event again I have to click out of the text area and click back in, then type again. The strange part about this is that when I am debugging and stepping through the word count updates without any issues.

I just need it to update as I am typing like when I am debugging.

My Blazor component:

<div class="row">
    <textarea id="test" class="form-control" @bind="text" @onkeypress="WordsLeft"></textarea>
    <p>Words left: @(MaxCount - CurrentWordCount)</p>
</div>

@code {
    [Parameter]
    public int MaxCount { get; set; }

    [Parameter]
    public string text { get; set; } = string.Empty;

    public int CurrentWordCount;

    public void WordsLeft()
    {
        CurrentWordCount = text.Split(' ').Length;
    }
}

Order of how it behaves: Open page (words left: 500) -> type a word (words left: 499) -> Type another 2 words (words left 499) -> click out of text area -> click back in to text area -> type another word (words left: 496)

Here's a working version of your code:

@page "/Test1"
<div class="row">
    <textarea id="test" class="form-control" @bind="text" @oninput="WordsLeft"></textarea>
    <p>Words left: @(MaxCount - CurrentWordCount)</p>
</div>

@code {
    public int MaxCount { get; set; } = 500;

    public string Text { get; set; } = string.Empty;

    public int CurrentWordCount;

    public void WordsLeft(ChangeEventArgs e)
    {
        CurrentWordCount = e.Value.ToString().Length;
    }
}

text only gets updated when you exit the control. The easiest way to get the actual entered value on each keystroke is through the ChangeEventArgs . Also it's generally better to use the oninput event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM