Calling a method in a child component
Component markup file: RpModal.Razor
1 2 3 4 5 6 7 8 |
@inherits RpModalBase @if (ShowConfirmation) { <div class="modal fade show d-block" tabindex="-1"> [Bootstrap modal HTML] </div> } |
Component code-behind file: RpModal.razor.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using Microsoft.AspNetCore.Components; namespace MyBlazorModal.Shared { public class RpModalBase : ComponentBase { protected bool ShowConfirmation { get; set; } = false; public void Show() { ShowConfirmation = true; StateHasChanged(); } } } |
Setting ShowConfirmation
to true makes the modal visible. Calling the Show
method sets ShowConfirmation
to true and calls StateHasChanged
.
There are two ways the parent component can call ShowConfirmation
:
Directly from code>@onclick</code with a lambda:
1 2 3 4 5 6 7 |
<h1 @onclick="() => rpmodal.Show()">Show dialog directly with <code>@onclick</code></h1> <RpModal @ref="rp"></RpModal> @code { protected RpModal rpmodal; } |
Or with a method in the parent component:
1 2 3 4 5 6 7 8 9 10 11 12 |
<h1 @onclick="ShowModal">Show modal with method!</h1> <RpModal @ref="rpmodal"></RpModal> @code { protected RpModal rpmodal; protected void ShowModal() { rpmodal.Show(); } } |