yavg
yavg

Reputation: 3061

how can I call a function from component A that is contained in component B and these components are on the same level

I have something like this:

My components

<ComponentA></ComponentA>
<ComponentB></Componentb>

    import { Component, OnInit } from "@angular/core";
    @Component({
      selector: "component",
      templateUrl: "<button (click)=""></button>" //I need call fn_componentB
    })
    export class ComponentA implements OnInit {
      constructor() {}
      ngOnInit() {}

    }

    import { Component, OnInit } from "@angular/core";
    @Component({
      selector: "component",
      templateUrl: "./component.component.html",
      styleUrls: ["./component.component.scss"]
    })
    export class ComponentB implements OnInit {
      constructor() {}
      ngOnInit() {}

      fn_componentB() {
        alert("call");
      }
    }

I want that when I click on a button contained in my component A, a function is called which is contained in my component B(fn_componentB). How can I do it? I have tried viewchild, and output but am not sure in this case what is best.

Upvotes: 0

Views: 51

Answers (1)

DaggeJ
DaggeJ

Reputation: 2201

You could do this by giving component B an ID and calling a public method in it like this;

<div>
    <app-component-a (click)="compB.doSomething();"></app-component-a>
    <app-component-b #compB></app-component-b>
</div>

Component B defines doSomething as a normal public method;

public doSomething() { }

Upvotes: 1

Related Questions