Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to share data between two child components in Blazor

I have this code.

<ParentComponent>
    <ChildComponet>
         @renderFragment
    </ChildComponent>
    <ChildComponetn>
       <GridComponent Data="@dataList"/>
    </ChildComponent>
</ParentComponent>

where @renderFragment is dynamically render componet and Grid componet is list of some data with actions like "add new", "edit record", "delete".

If we click "add new", form for add new record is opened dynamically in @renderFragment and we want to refresh grid data after submit form but we don't know how to share some data between two child components. Same is about edit form, when some record is edited, we need to refresh grid component to show edited data. If need more code and data about it please comment.

like image 586
Kristijan Mihaljinac Avatar asked May 27 '20 11:05

Kristijan Mihaljinac


People also ask

How do you share data between two child components?

A simple way is to set an output with @Output in your child component2 as an eventemitter and emit a event with the message passed as a data of it when a button is clicked. Then, listen to this event in your parent component and update a property that is set as an input of your child component1 when the event occurs.

How do you pass data from child to parent in Blazor?

Child component to parent component communication Child component (DisplayEmployee Component) should notify the parent component (EmployeeList Component) that a record is deleted so the parent component can remove the respective employee card from the list of employees. For this the child component exposes an event.

How will you send data from a child component to the parent component?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .

How to share data from child component to parent component in Blazor?

In Angular, we use EventEmitter along with Output decorators to share data from child to parent component. In Blazor, we use “EventCallback” parameter to emit value from child component to parent component. Please note, “Changed” suffix is added to the value property parameter.

How do I pass data between components in Blazor?

Blazor has at least five methods of passing or sharing data between components. The route parameters and querystring methods allow you to pass data in a component’s URL. The component parameters and cascading parameters methods allow you to pass data from parent component to child components when nesting is involved.

Can we share the data between parent and child components?

We will share the data between parent and child components and vice versa too. Blazor is a new framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET itself.

What is a Blazor app?

Blazor apps are the collection of multiple Blazor components interacting with each other and we are also allowed to use child components inside other parent components. In real-world apps, it is a very common scenario to pass data or event information from one component to another component.


1 Answers

You may define a class service that implements the State pattern and the Notifier pattern to handle the state of your objects, pass state to objects, and notify subscriber objects of changes.

Here's a simplified example of such service, which enables a parent component to communicate with his children.

NotifierService.cs

public class NotifierService
{
    private readonly List<string> values = new List<string>();
    public IReadOnlyList<string> ValuesList => values;

    public NotifierService()
    {

    }

    public async Task AddTolist(string value)
    {
        values.Add(value);

        await Notify?.Invoke();
        
    }

    public event Func<Task> Notify;
}

Child1.razor

    @inject NotifierService Notifier
@implements IDisposable

<div>User puts in something</div>
<input type="text" @bind="@value" />
<button @onclick="@AddValue">Add value</button>

@foreach (var value in Notifier.ValuesList)
{
    <p>@value</p>
}


@code {
    private string value { get; set; }

    public async Task AddValue()
    {
        await Notifier.AddTolist(value);
    }

    public async Task OnNotify()
    {
        await InvokeAsync(() =>
        {
            StateHasChanged();
        });
    }


    protected override void OnInitialized()
    {
        Notifier.Notify += OnNotify;
    }


    public void Dispose()
    {
        Notifier.Notify -= OnNotify;
    }
}

Child2.razor

    @inject NotifierService Notifier

<div>Displays Value from service and lets user put in new value</div>

<input type="text" @bind="@value" />

<button @onclick="@AddValue">Set Value</button>

@code {
    private string value { get; set; }
    public async Task AddValue()
    {
        await Notifier.AddTolist(value);
         
    }

}

Usage

@page "/"

 <p>
    <Child1></Child1>
 </p>
<p></p>
<p>
   <Child2></Child2>
</p>

Startup.ConfigureServices

services.AddScoped<NotifierService>();

Hope this helps...

like image 134
enet Avatar answered Sep 18 '22 14:09

enet