Search code examples
angulartypescripteventscomponentsselector

How can I call a function from another component while keeping the other component generic in Angular?


I am trying get component1 to trigger a function in component2, but component2 needs to stay generic so it can be accessed by any component. Without making it generic, my code looks like this:

component1:

@Output() component2function = new EventEmitter<any>();
...
this.component2function.emit({ param1, param2 });

component2 selector:

<component1 (component2function)="component2function($event)"> </component1>

This should trigger component2function but now I want to trigger that same function without explicitly using the component1 selector, so that component2function can be triggered by components other than component1. How can I do this?


Solution

  • I would put the function into a shared service instead. That way, all you need to do is provide the service via the constructor of each component. Component 1, component 2, and component 3 then can all access this shared function easily.

    Service.ts

    @Injectible({
       providedIn: "root"
    })
    export class SharedService {
        sharedFunction() {
            let theSolution = ....;
    
            return theSolution;
        }
    }
    

    Then in the component.ts

    @Component({
      selector: "component1",
      templateUrl: "./component1.component.html",
      styleUrls: ["./component1.component.css"]
    })
    export class Component1 implements OnInit {
    
        constructor(private sharedService: SharedService) {}
    
        ngOnInit() {
            this.genericFunction();
        }
    
        genericFunction() {
            this.sharedService.sharedFunction();
        }
    }
    

    From there you can just call either the service function right from the html or call the component function like above from the html. If you're managing data, the state will be more predictable in a shared service.