Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementReference to conditionally created element in Blazor

I'm trying to set focus to input control which is conditionally rendered. I'm setting ElementReference but it's id and context are both null.

<button @onclick="ToggleInput">Show input</button>
@if(showInput) {
    <input @ref="inputRef" type="text"/>
}

@code {
    private ElementReference inputRef;
    private bool showInput;

    async void ToggleInput() {
        showInput = !showInput;

        await inputRef.FocusAsync();
    }
}

When I press the button it shows this error in console:

System.InvalidOperationException: ElementReference has not been configured correctly

Full error message:

enter image description here

Working example with error https://blazorrepl.com/repl/wbueaMPK28hf2NNv09

like image 203
Sousuke Avatar asked Sep 02 '26 21:09

Sousuke


1 Answers

This seems to work and didn't have to be a separate component. I stuck it right on the start page.

<button @onclick="ToggleInput">Show input</button>
@if (showInput)
{
    <input @ref="inputRef" type="text" />
}

@code {
    private ElementReference inputRef;
    private bool showInput;

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (showInput) await inputRef.FocusAsync();
    }

    void ToggleInput()
    {
        showInput = !showInput;
    }
}
like image 164
Nikki9696 Avatar answered Sep 04 '26 09:09

Nikki9696



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!