Is it possible to Two-way bind an collection in Blazor child component?
TLDR; A property of type list in an object is set to null when the ValueChanged EventCallBack handler is executed, and this throws NullReferenceExceptions because its set to null in the pages.
I have the following example:
public class Person
{
public string FullName { get; set; }
public List<string> NickNames { get; set; } = new List<string>();
}
The main page: Index.razor
<h1>@Mario.FullName - @string.join('-', Mario.NickNames)</h1>
<NicknamesListComponent @bind-Nicknames="Mario.NickNames" />
@code{
public Person Mario { get; set; } =
new Person() { FullName = "Mario", NickNames = new List<string> {"Super", "Mama" , "Mia"} }
}
The child component: NicknamesListComponent.razor
<ul>
@for(int i = 0; i < Nicknames.Count; i++)
{
@var index = i;
<li>
@Nicknames[index]
<a @onclick="() => RemoveNickname(index)">Remove</a>
</li>
}
</ul>
@code {
[Parameter]
public List<string> Nicknames { get; set; }
[Parameter]
public EventCallback<List<string>> NicknamesChanged { get; set; }
public async Task RemoveNickname(int index)
{
Nicknames.RemoveAt(index);
//////////////////////////////////////////////////////////
// When executing NicknamesChanged. the User.Nicknames property is completly cleared and
// set to NULL... this throws exceptions everywhere in the index.blazor
await NicknamesChanged.InvokeAsync();
}
}
If I remove the NicknamesChanged, then the list with the Delete button works... but this time the parent is not notified of changes and the nicknames stay the same...