Reputation: 579
Given a Child component:
<p>Name: @Name</p>
@code {
[Parameter]
public string Name { get; set; } = "Scooby Do";
[Parameter]
public EventCallback<string> NameChanged { get; set; }
}
And a Parent component with two-way binding on the Name
property:
Name: <InputText @bind-Value=@Name/>
<ChildComponent @bind-Name=@Name />
@code {
public string Name { get; set; }
}
It appears the ChildComponent.Name
is overwritten by the null value from the ParentComponent.Name
property.
I would like the value "Scooby Do" from the Child to be bound up to the Parent as the default value.
How do I enable the two-way binding but use the Child component's default values?
Upvotes: 0
Views: 143
Reputation: 273611
To apply the default rule once, add this to the Child:
[Parameter]
public string Name { get; set; } // = "Scooby Do";
...
protected override async Task OnInitializedAsync()
{
if (string.IsNullOrEmpty(Name) )
{
await NameChanged.InvokeAsync("Scooby Do");
}
}
when you want to replace it with "Scooby Do" again when the user empties the textbox then override OnParametersSetAsync instead, with the same code.
Upvotes: 1