Simple Way To Execute A Function In A Component From Another Component

Introduction

In this post, we will execute a function in a component from another component in Angular. We will pass the data from one component to another component as well. For this, we are using EventEmitter service. In Angular, a component can emit an event using @Output and EventEmitter. The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event. We can use various options to execute functions from another component in angular.

Create a new Angular Project using Angular CLI
 
I am using Angular 7.
 
Simple Way To Execute A Function In A Component From Another Component 
  1. ng new EventEmitterExample   

In Angular 7, we can create a routing module along with the project creation. It will take some moments to create all the node modules. Our project will be created after some time.

We can create three components. “Home”, “First” and “Second” respectively.

We need to change the folder to “EventEmitter” in command prompt and create “Home” component.

Simple Way To Execute A Function In A Component From Another Component 
  1. ng g c Home  
Now create “First” and “Second” respectively.
  1. ng g c First  
  2. ng g c Second  

We can open the code in any IDE and edit the code. I am using Visual Studio Code for editing the code.

We can edit the “app.component.html” file with the below code.
 
app.component.html
  1. <ul>    
  2.   <li class="active"><a  routerLink="home">Home Component</a></li>    
  3.   <li><a routerLink="first">First Component</a></li>    
  4.   <li><a routerLink="second">Second Component</a></li>    
  5. </ul>    
  6. <router-outlet></router-outlet>   

We can create a function inside the “first.component.ts” file and call from “first.component.html” file.

first.component.ts
  1. import { Component, OnInit } from '@angular/core';    
  2.     
  3. @Component({    
  4.   selector: 'app-first',    
  5.   templateUrl: './first.component.html',    
  6.   styleUrls: ['./first.component.css']    
  7. })    
  8. export class FirstComponent implements OnInit {    
  9.     
  10.   constructor() { }    
  11.     
  12.   ngOnInit() {    
  13.   }    
  14.     
  15.   firstFunction() {    
  16.     alert( 'Hello ' + '\nWelcome to C# Corner \nFunction in First Component');    
  17.   }    
  18. }    
first.component.html
  1. <p>    
  2.   First Component    
  3. </p>    
  4.     
  5. <div>    
  6.   <input type="button" value="Call Function" (click)="firstFunction()">    
  7. </div>    

We can modify the “app-routing.module.ts” file.

app-routing.module.ts

  1. import { NgModule } from '@angular/core';    
  2. import { Routes, RouterModule } from '@angular/router';    
  3. import { HomeComponent } from './home/home.component';    
  4. import { FirstComponent } from './first/first.component';    
  5. import { SecondComponent } from './second/second.component';    
  6.     
  7. const routes: Routes = [    
  8.   { path: '',    
  9.     redirectTo: '/home',    
  10.     pathMatch: 'full'    
  11.   },    
  12.   { path: 'home', component: HomeComponent },    
  13.   { path: 'first', component: FirstComponent },    
  14.   { path: 'second', component: SecondComponent }    
  15. ];    
  16.     
  17. @NgModule({    
  18.   imports: [RouterModule.forRoot(routes)],    
  19.   exports: [RouterModule]    
  20. })    
  21. export class AppRoutingModule { }    
We need a service to create EventEmitter instance. We can create this service using Angular CLI.
 
Simple Way To Execute A Function In A Component From Another Component 
  1. ng g s event-emitter  
Do not forget to add service provider reference in “app.module.ts” file.
 
Simple Way To Execute A Function In A Component From Another Component 
 
We can modify the “event-emitter.service.ts” file with below code.
 
event-emitter.service.ts
  1. import { Injectable, EventEmitter } from '@angular/core';    
  2. import { Subscription } from 'rxjs/internal/Subscription';    
  3.     
  4. @Injectable({    
  5.   providedIn: 'root'    
  6. })    
  7. export class EventEmitterService {    
  8.     
  9.   invokeFirstComponentFunction = new EventEmitter();    
  10.   subsVar: Subscription;    
  11.     
  12.   constructor() { }    
  13.     
  14.   onFirstComponentButtonClick() {    
  15.     this.invokeFirstComponentFunction.emit();    
  16.   }    
  17. }    
Simple Way To Execute A Function In A Component From Another Component 
 
We have defined an EventEmitter variable “invokeFirstComponentFunction” and a Subscription variable “subsVar”.
 
invokeFirstComponentFunction” variable will be used in another method “onFirstComponentButtonClick” to emit the event and “subsVar” will be used later in event subscription.
 
We can go to “second.component.ts” component and create an event emitter service variable in the constructor. We will also create a function to invoke the EventEmitter method in service.
 
second.component.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. import { EventEmitterService } from '../event-emitter.service';    
  3.     
  4. @Component({    
  5.   selector: 'app-second',    
  6.   templateUrl: './second.component.html',    
  7.   styleUrls: ['./second.component.css']    
  8. })    
  9. export class SecondComponent implements OnInit {    
  10.     
  11.   constructor(    
  12.     private eventEmitterService: EventEmitterService    
  13.   ) { }    
  14.     
  15.   ngOnInit() {    
  16.   }    
  17.     
  18.   firstComponentFunction(){    
  19.     this.eventEmitterService.onFirstComponentButtonClick();    
  20.   }    
  21. }    
Simple Way To Execute A Function In A Component From Another Component 

We have created a “firstComponentFunction” to call the event emitter service. This will automatically invoke the event in service.

We can modify the “second.component.html” with the below code to create a button in UI.
 
second.component.html
  1. <p>    
  2.   Second Component    
  3. </p>    
  4.     
  5. <div>    
  6.   <input type="button" value="Call First Component Function" (click)="firstComponentFunction()">    
  7. </div>    
We can modify the “first.component.ts” again to subscribe the even emitter event.
 
first.component.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. import { EventEmitterService } from '../event-emitter.service';    
  3.     
  4. @Component({    
  5.   selector: 'app-first',    
  6.   templateUrl: './first.component.html',    
  7.   styleUrls: ['./first.component.css']    
  8. })    
  9. export class FirstComponent implements OnInit {    
  10.     
  11.   constructor(    
  12.     private eventEmitterService: EventEmitterService    
  13.   ) { }    
  14.     
  15.   ngOnInit() {    
  16.     if (this.eventEmitterService.subsVar==undefined) {    
  17.       this.eventEmitterService.subsVar = this.eventEmitterService.    
  18.       invokeFirstComponentFunction.subscribe((name:string) => {    
  19.         this.firstFunction();    
  20.       });    
  21.     }    
  22.   }    
  23.     
  24.   firstFunction() {    
  25.     alert( 'Hello ' + '\nWelcome to C# Corner \nFunction in First Component');    
  26.   }    
  27. }    
Simple Way To Execute A Function In A Component From Another Component 
 
We have subscribed the “invokeFirstComponentFunction” event in event emitter service and called the “firstFunction” method inside it.
 
Our code is ready now. We can run the application. We can click the first component link.
 
Simple Way To Execute A Function In A Component From Another Component
 
We can click the “Call Function” button. It will call the function in the first component. 
 
Simple Way To Execute A Function In A Component From Another Component 
Now we can click the second component link and click the “Call First Component Function” button. It will execute the function from the first component and will show the same message box as given below.
 
Simple Way To Execute A Function In A Component From Another Component 
We have successfully executed the function from another component.
 
We can even pass any data through this event emitter. We can modify the event emitter service by passing a “name” parameter.
 
Simple Way To Execute A Function In A Component From Another Component 

We must modify the “first.component.ts” and “second.component.ts” files too.

first.component.ts” file.
 
Simple Way To Execute A Function In A Component From Another Component 
 
second.component.ts” file
 
Simple Way To Execute A Function In A Component From Another Component 
 
We can modify the “first.component.html” with the below code.
 
first.component.html
  1. <p>    
  2.   First Component    
  3. </p>    
  4.     
  5. <div>    
  6.   <input type="text" #name>    
  7.   <br>    
  8.   <input type="button" value="Call Function" (click)="firstFunction(name.value)">    
  9. </div>    

Modify the “second.component.html” with the below code.

second.component.html
  1. <p>    
  2.   Second Component    
  3. </p>    
  4.     
  5. <div>    
  6.   <input type="text" #name>    
  7.   <br>    
  8.   <input type="button" value="Call First Component Function" (click)="firstComponentFunction(name.value)">    
  9. </div>    
We can run the application again and click first component and then click second component.
 
Simple Way To Execute A Function In A Component From Another Component 
We have successfully passed data from one component to another component and called the function.
 
In this post, we have created an event emitter service and executed a function in a component from another component. We have passed the data from one component to another component too.