Home > Net >  Angular - on button click run function in different component
Angular - on button click run function in different component

Time:02-03

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!

CodePudding user response:

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

CodePudding user response:

To call the function from Component B in Component A, you can use a service to communicate between the two components. You can create a shared service that both components inject, and use it to call a function in one component from the other.

Here's an example of how to do it:

1.Create a shared service:

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class SharedService {

  scrollToTop() {
    // implementation of the scrollToTop function
  }
}

2.Inject the service in both Component A and Component B:

import { SharedService } from './shared.service';

@Component({
  // ...
})
export class ComponentA {
  constructor(private sharedService: SharedService) {}

  onButtonClick() {
    this.sharedService.scrollToTop();
  }
}

import { SharedService } from './shared.service';

@Component({
  // ...
})
export class ComponentB {
  constructor(private sharedService: SharedService) {}

  ngOnInit() {
    this.sharedService.scrollToTop = () => {
      // scroll to top logic
    };
  }
}

This way, when you call this.sharedService.scrollToTop() in Component A, it will trigger the scroll to top logic defined in Component B.

  • Related