Home > Software design >  How to call a function in a parent razor component from a child item in blazor?
How to call a function in a parent razor component from a child item in blazor?

Time:05-05

I want to create a templated table component following the example in the microsoft documentation.

Here I want to add a sorting function to the table:

// This is a function in the code-behind of TableTemplate.razor
public void SortSourceList(/*some args*/)
{
    // sort based on given args
}

The question is the following. I want this function to be accessible from the children, for example the TableHeader items:

 @page "/somepage
 <TableTemplate Items="pets" Context="pet">
    <TableHeader>
        <th>
             <button  
                 @onclick=<!--call the sorting function from here-->>
        </th>
    </TableHeader>
    <RowTemplate>
        ...
    </RowTemplate>
</TableTemplate>
@code{ // page related code - don't want to handle anything concerning the table here }

I know this could be done by passing down the instance of TableTemplate as a CascadingParameter, but how to get this in a normal html item, which isn't a razor component? Also I don't necessarily want to have to add a TableTemplate instance as class property to any child components (which as far as I know is needed to access a cascading parameter?), so I was wondering if one could pass the function or an event directly?

CodePudding user response:

You can use EventCallback inside the child component and call the parent function:

Parent

<_ChildComponentCall parentFunction="SortSourceList"></_ChildComponent>

public void SortSourceList(/*some args*/)
{
    // sort based on given args
}

Child

<TableTemplate Items="pets" Context="pet">
    <TableHeader>
        <th>
             <button  
                 @onclick="() => parentFunction.InvokeAsync()"
        </th>
    </TableHeader>
    <RowTemplate>
        ...
    </RowTemplate>
</TableTemplate>
@code
[Parameter]
public EventCallback parentFunction { get; set; }

After you run the function you can save the sorting data in a service variable, and call that variable from the child.

CodePudding user response:

<TableHeader>
        <th></th>
        <th>ID</th>
        <th><a href="" @onclick="Sort" role="button">Name</a></th>
  </TableHeader>

@code
{

private void Sort()
{
        pets = pets.OrderBy(pet => pet.Name).ToList();
       
 }

}
  • Related