child component interact with parent component blazor
// 2 methods shown here
[Parent.razor]
@page "/ParentComponent"
<h1>Parent Component</h1>
<ChildComponent @bind-Password="_password" />
@code {
private string _password;
}
[ChildComponent.razor]
<h1>Child Component</h1>
Password:
<input @oninput="OnPasswordChanged"
required
type="@(_showPassword ? "text" : "password")"
value="@Password" />
<button class="btn btn-primary" @onclick="ToggleShowPassword">
Show password
</button>
@code {
private bool _showPassword;
[Parameter]
public string Password { get; set; }
[Parameter]
//VARIABLE MUST BE [var] + "Changed"
public EventCallback<string> PasswordChanged { get; set; }
private Task OnPasswordChanged(ChangeEventArgs e)
{
Password = e.Value.ToString();
return PasswordChanged.InvokeAsync(Password);
}
private void ToggleShowPassword()
{
_showPassword = !_showPassword;
}
}
// SECOND METHOD
[Child.razor]
<button @onclick="@(() => OnClick.InvokeAsync("Hello from ChildComponent"))">Click me</button>
@code {
[Parameter] public EventCallback<string> OnClick { get; set; }
}
[Parent.razor]
<ChildComponent OnClick="ClickHandler"></ChildComponent>
<p>@message</p>
@code {
string message = "Hello from ParentComponent";
void ClickHandler(string newMessage)
{
message = newMessage;
}
}