blazor foreach component update parent

Viewed 47

I have this on my razor page:

 @foreach (AanmeldingItem ai in Aanmeldingen.Aanmeldingen)
      {
        <NieuweAanmeldingScherm Aanmelding=@ai SL=@SL />
      }

The component "NieuweAanmeldingScherm" has a bunch of divs and inputtexts to gather some data. On the same page as the above foreach I have a button to add a new item. When I click this button it adds a new "AanmeldingItem" to "Aanmeldingen.Aanmeldingen" which is a list of "AanmeldingItem".

My problem is that when I enter some data it is not updated to the item in the list.

How does this work in Blazor (I'm just starting with it)?

so basically:

@foreach (MyClass myclass in MyClasses) 
{
  <MyComponent Myclass=@myclass />
}

MyComponent:

<InputText @bind-value=@myclass.item1 />
<InputText @bind-value=@myclass.item2 />

@code 
{
  [parameter]
  public MyClass myclass {get;set;}

}

Add button on the page containing the foreach loop:

<div class="form-control nieuwAanmeldItem" @onclick="NieuwItem" />

How do I make it so that MyClasses is updated with the info from the inputtexts?

2 Answers

Your loop is missing a @key directive, which gives Blazor a way to identify each instance of the component when rendering.

@foreach (AanmeldingItem ai in Aanmeldingen.Aanmeldingen)
{
  <NieuweAanmeldingScherm @key=ai Aanmelding=@ai SL=@SL />
}

Here, I have used the AanmeldingItem instance as the key, but if that class has a suitable unique int,string or some other simple type, use that instead as it will be better for performance.

I have figured out what I was doing wrong.

Mister Magoo's answer wasn't really needed, but I implemented it anyway. According to Microsoft it should work automatically but now I'm sure it works.

The problem was that I re-initialised the parameter on the "NieuwAanmeldingScherm". This caused to sever the link with the list from the foreach in the parent.

So this is what I did:

  [Parameter]
  public AanmeldingItem Aanmelding { get; set; }

  protected override void OnInitialized()
  {
    Aanmelding = new AanmeldingItem();    

    base.OnInitialized();
  }

And that is wrong since the parameter is already initialized in the parent.

Related