spindi598
spindi598

Reputation: 351

How to access a function from sibling component in blazor?

I have two different components, one isn't nested in the other, they are seperate, but will be seen at the same time in the same layout.

Component 1

@code {
    public void Tester()
    {
        Console.WriteLine("worked");
    }
}

Component 2

@code {
    Component1 c1 = new Component1();

     c1.Tester();
}

component 2 insists that c1.Tester() does not exist.

Is there a way around this so that I can access the Tester function in component 1?

Upvotes: 3

Views: 526

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273169

The call to c1.Tester() should of course be inside a method:

@code {
    Component1 c1 = new Component1();

  void SomeMethod()
  {
     c1.Tester();   // this should work
  }
}

If this is not it then post the exact code and literal error message.

Upvotes: 0

Vencovsky
Vencovsky

Reputation: 31565

You should use @ref to get Component1 method and pass it as a parameter to Component2

<Component1 @ref="Component1Ref" />
<Component2 Tester="@Tester" />

@code {
    Component1 Component1Ref;

    void Tester()
    {
        Component1Ref.Tester();
    }
}

Here is a working example.

Upvotes: 2

Related Questions