Search code examples
blazorrazor-components

Do a function on click in component


I have a button :

<BSButton Color="Color.Info" @onclick="LoadCategoryDetailsModal">
     <i class="fal fa-plus-circle mr-1"></i>Add New Category
</BSButton>

I have a component :

<CategoryDetails CategoryDetailModalTitle="@categoryDetailModalTitle">
</CategoryDetails>

In the component, I have a function to toggle the modal (show/hide); the modal is hidden by default

@using BlazingShop.Services
@inject ICategoryService CategoryService

<BSModal @ref="CategoryDetailsModal" IsCentered="true">
    <BSModalHeader OnClick="@OnToggle">@CategoryDetailModalTitle</BSModalHeader>
    <BSModalBody><p>Modal body text goes here.</p></BSModalBody>
    <BSModalFooter>
        <BSButton Color="Color.Primary">Save Changes</BSButton>
        <BSButton Color="Color.Secondary" @onclick="@OnToggle">Close</BSButton>
    </BSModalFooter>
</BSModal>

@code {

    BSModal CategoryDetailsModal;

    [Parameter]
    public string CategoryDetailModalTitle { get; set; }

    void OnToggle(MouseEventArgs e)
    {
        CategoryDetailsModal.Toggle();
    }
}

I try to toggle the modal from the parent component.

Can you help me please ?

When I click on this button (in parent component):

<BSButton Color="Color.Info" @onclick="LoadCategoryDetailsModal">
    <i class="fal fa-plus-circle mr-1"></i>Add New Category
</BSButton>

I want to to this function inside the child component:

CategoryDetailsModal.Toggle();

Solution

  • Hey I just find the answer ! Add the @ref="Modal" in your Component :

    <CategoryDetails CategoryDetailModalTitle="@categoryDetailModalTitle" @ref="@Modal"></CategoryDetails>
    

    in @Code section :

    private CategoryDetails Modal { get; set; }
    

    In the method when you click on the button :

     private void LoadCategoryDetailsModal()
        {
            category = new Category();
            categoryDetailModalTitle = "Add New Category";
            Modal.Toggle();
        }
    

    Toggle it's a method I made in the Child component :

    public void Toggle()
        {
            CategoryDetailsModal.Toggle();
        }