PreventDefault on Blazor input

Ok, this is a bit dirty tricky: remove the last char to override user input key:

<input type="text" 
       value="@PetitionInput" 
       onkeydown="@PetitionHandleKeyDown"
       onkeyup="@PetitionHandleKeyUp" 
        />

// ...
private int _petitionCharStep = 0;
private string _petition = "This is a dummy text";
public string PetitionInput { get; set; } = string.Empty;

void PetitionHandleKeyDown(UIKeyboardEventArgs arg) {
    if (_petitionCharStep >= _petition.Length  )
    {
        PetitionInput = _petition.Substring(0, _petition.Length-1 );
        _petitionCharStep--;
    }
}

void PetitionHandleKeyUp(UIKeyboardEventArgs arg) {
    if (_petitionCharStep < _petition.Length  )
    {
        PetitionInput += _petition[_petitionCharStep];
        _petitionCharStep++;
    }        
}

enter image description here

Test it at blazorfiddle.


You can think a little differently in Blazor.

Rather than using "bind" and preventing the keystroke, you can set the "value" and handle the "oninput" event, like this:

https://blazorfiddle.com/s/azdn892n

@page "/"
<h1>Start typing something...</h1>
<input type="text" value="@PetitionInput" oninput="@PetitionHandleKeyDown" />

@functions {
    private int _petitionCharStep = 0;
    private string _petition = "This is a dummy text";
    public string PetitionInput { get; set; } = string.Empty;

    void PetitionHandleKeyDown(UIChangeEventArgs arg) {
        PetitionInput = _petition.Substring(0,++_petitionCharStep);
        Console.WriteLine(PetitionInput);
    }
}

Sample Typing F repeatedly

I can't imagine why you would want to do this, and there are many extra things you need to do to cover backspaces, arrow keys, tab etc...