'Set focus on dynamic generated InputNumber by using @ref
I created a group of
InputNumberbyforeachprivate InputNumber<double?> OnfocusRef; //This should be dynmic but I don't know how!!! @foreach(employee in Employees){ { <EditForm Model="employee"> <InputNumber @bind-Value="employee.Monday" @ref="OnfocusRef" @onfocus=@(() => OnfocusHandler(employee)) // other inputNumbers with rest days of the week (Tuesday, Wednesday ..) .... </EditForm> }After rendering the code up, I get a rows of inputs days for each Employee like this:
By using a tab, user can move between input box, if user jump to the next row, I have to save the changes of the previous row because it is a different employee.
private FocusedEmployee {get; set;} private async Task OnfocusHandler(Employee employee) { //first lading of the page if(FocusedEmployee is null) { FocusedEmployee = employee; } //jump to next row else if(FocusedEmployee.Id != employee.Id) { await UpdateEmployee(FocusedEmployee) if(OnfocusRef.Element.HasValue) { // Problem here! await OnfocusRef.Element.Value.FocusAsync(); } else { FocusedEmployee= employee; } } }My question: How can I set focus on the first input box of the current Employee after each saving of pre Employee? I have to loop and create a list of
EditFormand eachEditFormhas a list of InputRadio, my problem with@refis not any more unique !
Solution 1:[1]
You can deal with Refs dynamically:
@foreach (var t in PotatosAndReferences)
{
<input type="text" @key="@t.Potato.Id" @bind="t.Potato.Name" @ref="@t.Ref" />
}
<br>
<button @onclick="_ => GoN(0)">Focus first</button>
<button @onclick="_ => GoN(15)">Focus 16</button>
@code {
public class Potato
{
public int Id {get; set; }
public string Name {get; set;} = default!;
}
public class PotatoAndReference
{
public Potato Potato {get; set;} = default!;
public ElementReference? Ref {get; set;} = null;
}
public List<Potato> Potatos
=
Enumerable.Range(1, 50)
.Select(i => new Potato() {Id = i, Name = $"Potato {i}"}).ToList();
public List<PotatoAndReference> PotatosAndReferences = default!;
protected override void OnInitialized()
=>
PotatosAndReferences =
Potatos
.Select(p => new PotatoAndReference(){Potato = p}).ToList();
protected async Task GoN(int n)
=>
await PotatosAndReferences.ElementAt(n).Ref!.Value.FocusAsync();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dani herrera |


