Home > OS >  Blazor, select an item in for loop of components and deselect the others
Blazor, select an item in for loop of components and deselect the others

Time:10-30

In Blazor Webassembly version 5:

I have a for loop which iterates over data items to show them and a user should be able to select the items by clicking. What is the best way to achieve that? I want to select the selected PersonItem but deselect the other components. The problem is with deselecting the others.

PersonItem.Razor:

@if (Person!= null)
{
    <div @onclick="InvokeOnClick" style="@GetStyle()">@Person.Name</div>
}
@code {


    [Parameter] public PersonPerson { get; set; } = null;
    [Parameter] public bool IsSelected { get; set; }=false;
    [Parameter] public EventCallback<Person> OnClick { get; set; }
    private string GetStyle() => IsSelected ? "cursor:default;color:blue" : "cursor:pointer";

    protected override Task OnParametersSetAsync()
    {
        StateHasChanged();
        return base.OnParametersSetAsync();
    }

    private async Task InvokeOnClick()
    {
      IsSelected = true;
      await OnClick.InvokeAsync(Person);
    }
}

MyPage.razor :

@inject IPersonRepo personRepo;



@if (PersonList !)
{
    foreach (var person in PersonList)
    {
        <PersonItem Person="@person"></PersonItem>
    }
}
else
{
    <div>Not Yet!</div>
}


@code {
    public List<Person>? PersonList { get; set; } = null;

    protected async override Task OnInitializedAsync()
    {
        await GetAllPersons(null);
        await base.OnInitializedAsync();
    }


    public async Task GetAllPersons(EventArgs e)
    {
        PersonList = await personRepo.GetAllPersons();
    }
}

CodePudding user response:

You already have most of the ingredients. The requirement is fulfilled when you use OnCLick and IsSelected:

foreach (var person in PersonList)
{
    <PersonItem Person="@person" 
           OnClick="SelectPerson" 
           IsSelected="person==selectedPerson" />
}

and in @code:

   
Person selectedPerson = null;

void SelectPerson(Person person)
{
   selectedPerson = person;
}
  • Related