Reputation: 1
I have looked thru google and only found solutions for when you can reach functions/values from child to parent and the other way around but not from chil to child.
Parent Component, container for child components
//PARENT
<h3>ParentComponent</h3>
<Child_1_Component></Child_1_Component>
<Child_2_Component></Child_2_Component>
<h3>Child_1_Component</h3>
//CHILD 1
<h1>User puts in something</h1>
<input type="text"/>
<button @onclick="@(() => getValue(10))"></button>
@code {
List<WhatEver> whatEvers = new List<WhatEver>();
public void getValue(int value)
{
var message = "something";
for (int i = 0; i < value; i++)
{
var whatever = new WhatEver();
whatever.Name = message;
whatEvers.Add(whatever);
}
//Sends value to Service
}
}
CHILD 2 Displays via Service what the user put in Child 1 and gives the user posibility to change the value.
<h3>Child_2_Component</h3>
<h1>Displays Value from service and lets user put in new value</h1>
<input type="text" />
<button @onclick="@(() => getValue(10))"></button>
@*Here I want to use the funcction getValue(x) in Child_1_Component*@
Upvotes: 0
Views: 79
Reputation: 1198
Define a Worker class and put the getValue(int value) in.
public class Worker{
public object getValue(int value){
//[...]
return something;
}
}
Then there are two possibilities:
Solution 1
Create an instance of Worker in the parent of both child items and put it to both childs.
//PARENT
<h3>ParentComponent</h3>
<Child_1_Component Worker="@MyWorker"></Child_1_Component>
<Child_2_Component Worker="@MyWorker"></Child_2_Component>
<h3>Child_1_Component</h3>
@code {
private Worker MyWorker{ get; set; }
protected override void OnInitialized()
{
MyWorker = new Worker();
}
}
And then the Child, where Worker is same object in both childs:
//CHILD 1
<h1>User puts in something</h1>
<input type="text"/>
<button @onclick="@(() => Worker.getValue(10))"></button>
@code {
[Parameter]
public Worker Worker { get; set; }
}
Solution 2:
You move getValue(int value) into an Service and define it in Startup.cs, then also both childs have the same instance.
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
[...]
services.AddScoped<Worker>();
}
And then the Child, where Worker is same object in both:
//CHILD 1
@inject Worker MyWorker
<h1>User puts in something</h1>
<input type="text"/>
<button @onclick="@(() => MyWorker.getValue(10))"></button>
Upvotes: 1