Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

How do I communicate between two sibling Blazor components?

$
0
0

I have a Blazor page with two components. One component has a button which generates a random number when clicked. The other component has a text area which should display the generated random number.

<h1>Parent Page</h1><ProvideNumberComponent /><DisplayNumberComponent  />@code {}
<h3>Provides Number</h3><button class="btn btn-primary" @onclick="CalculateNumber">Provide Number</button>@code {    private void CalculateNumber(MouseEventArgs e)    {        Random rnd = new Random();        Int32 nextNumber = rnd.Next();    }}
<h3>Displays number</h3><textarea cols="9" rows="1" readonly style="font-family:monospace;" />@code {}

What is the cleanest way to get the number from the calculate sibling component to appear in the display sibling component?

A problem with my code is that the Random object is instantiated on every button click, instead of once on initialization. Is this best addressed by placing the Random object in a singleton service class, and injecting that into the calculate component?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>