Blazor Textarea update on variable change

Viewed 2056

I want a textarea to always show the value of a variable. But it only updates if I click a button. What can I do to update the textarea everytime the variable changes?

<button class="btn btn-primary" @onclick="Test">Test</button>
<textarea  type="text" name="configJson" id="configJson"  value="@inputString" rows="20" cols="50" />
@code {
private string inputString;
    private void Test()
    {
        inputString = inputString;
    }
}

I have code that changes the variable constantly but it does not update the textarea. The textarea is only updated if I click the button. What am I doing wrong? Thanks in advance!

1 Answers

What you need is StateHasChanged() method of ComponentBase class. This tells Blazor the data bindings (including one directional) needs updating. BTW, why are you using "value" attribute of textarea element? You should set its content. It is not input. See the example below:

@page "/"

<textarea>
  @Text
</textarea>

@code {

    public string Text { get; set; }
    int Counter { get; set; }

    protected override void OnInitialized() {
        base.OnInitialized();
        var timer = new System.Timers.Timer(1000);
        timer.Elapsed += (s, e) => {
            Counter++;
            InvokeAsync(() => {
                Text = $"Tick {Counter}";
                StateHasChanged();
            });
        };
        timer.Start();
    }

}
Related