Warm tip: This article is reproduced from serverfault.com, please click

Blazor event only works correctly while debugging

发布于 2021-10-20 21:02:38

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)

Questioner
asciik
Viewed
0
MrC aka Shaun Curtis 2021-10-21 05:29:40

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.