0

I'm trying to do a simple task in Angular but it's giving me some trouble.

I have 2 separate components with no relation between them, let's call them Component A and Component B - all I want is that when I press a button in Comp A to run a function in Comp B - the onClick event and corresponding function is already sorted, I just need to call a function that's coming from Comp B like in the example below:

Component-A.component.ts

onButtonClick() {
  //do something
  //call function from Comp B

  functionB();
}

Component-B.component.ts

functionB() {
  element.scrollTo({top: 0})
}

All I want is to call the function from Comp B inside the onClick function of my button from Comp A so that the container of Comp B is scrolled to top.

What would be the simplest way to achieve this? Thank you in advance!

2 Answers 2

3

Create a service which has a subject and inject in both the components. Do these 2 things:

  1. in component B, subscribe to the subject
  2. in component A, set the subject inside the function which you want to call

make sure to unsubscribe from the subject

one good example can be found here: https://medium.com/mobiosolutions/angular-communicating-between-components-with-observable-827180e43eb5

Sign up to request clarification or add additional context in comments.

Comments

0

Depending on the structure of the components you could use an EventEmmitter. Assuming you can refactor to this structure:

<parent-component>
  <component-a (clicked)="onComponentAClicked()"></>
  <component-b #compB><>
</parent-component>

The parent-component can listen for the component-a click event to be emitted. It can then call the public scrollToTop function on component-b by refencing the ChildView.

commponent-a

<button (click)="onButtonClick()">Click here</button>

...
export class ComponentA {
  @Output('clicked') public clicked = new EventEmitter();

  public onButtonClick() {
    this.clicked.next(true);
  }
}

parent-component

...
export class ParentComponent {
    @ViewChild('compB') public compB: ComponentB;

    public onComponentAClicked() {
      this.compB.scrollToTop();
    }
}

If you can't refactor to the above structure then as others suggested; a shared service would solve the issue. In the service you could consider adding a Subject and then subscribe to changes in component-b.

component-a

onButtonClicked() {
    this.scrollService.scrollToTop$.next(true);
}

component-b

ngOnInit(): void {
   this.scrollService.scrollToTop$.subscribe(() => this.scrollToTop());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.