I have a requirement to load new data into my form when a user clicks the up or down arrow. And the expectation is whatever cell has the focus, retains the focus after new data is loaded.
The following code can trap the keyboard input, and load the correct record into my form using data binding. However I find, the form loses focus as soon as new data gets bound.
MyComponent.razor:
<span @onkeypress="@KeyHandler" @onkeydown="@KeyHandler">
<EditForm Model="@CurrentRecord">
<DataAnnotationsValidator />
<ValidationSummary />
@Content
</EditForm>
</span>
@code {
[Parameter]
public RenderFragment Content { get; set; }
public List<MyModel> Data { get; set; } = new List<MyModel>();
private int currentIndex;
protected async Task KeyHandler(KeyboardEventArgs e)
{
if (e.Key == "DownArrow") await LoadNextRecord();
}
async Task LoadNextRecord()
{
CurrentRecord = Data.ElementAt(++currentIndex);
// Form loses focus here!!
}
}
Now I can implement a simple javascript to focus the first element when the data is re-binded. But my requirement is to keep the focus where it is. I could not find a generic way to get the focused element and then re-focus without having to assign an Id or an @ref for every element in my form.
Is there another way to solve this problem?
RenderFragment, try passing the form directly insideMyComponent. Probably it will work - VencovskyCurrentRecorddirectly, but only it's properties. AutoMapper would be usefull in this case. I think it's losing focus because it's changing the reference ofCurrentRecord, but if you only change the properties values, maybe it won't. - Vencovsky