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 serviceIn Angular, a component can emit an event using @Output and EventEmitterThe 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 6.
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. @Component({
  3.   selector: 'app-first',
  4.   templateUrl: './first.component.html',
  5.   styleUrls: ['./first.component.css']
  6. })
  7. export class FirstComponent implements OnInit {
  8.   constructor() { }
  9.   ngOnInit() {
  10.   }
  11.   firstFunction() {
  12.     alert( 'Hello ' + '\nWelcome to C# Corner \nFunction in First Component');
  13.   }
  14. }

first.component.html

  1. <p>
  2.   First Component
  3. </p>
  4. <div>
  5.   <input type="button" value="Call Function" (click)="firstFunction()">
  6. </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. const routes: Routes = [
  7.   { path: '',
  8.     redirectTo: '/home',
  9.     pathMatch: 'full'
  10.   },
  11.   { path: 'home', component: HomeComponent },
  12.   { path: 'first', component: FirstComponent },
  13.   { path: 'second', component: SecondComponent }
  14. ];
  15. @NgModule({
  16.   imports: [RouterModule.forRoot(routes)],
  17.   exports: [RouterModule]
  18. })
  19. 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. @Injectable({
  4.   providedIn: 'root'
  5. })
  6. export class EventEmitterService {
  7.   invokeFirstComponentFunction = new EventEmitter();
  8.   subsVar: Subscription;
  9.   constructor() { }
  10.   onFirstComponentButtonClick() {
  11.     this.invokeFirstComponentFunction.emit();
  12.   }
  13. }
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. @Component({
  4.   selector: 'app-second',
  5.   templateUrl: './second.component.html',
  6.   styleUrls: ['./second.component.css']
  7. })
  8. export class SecondComponent implements OnInit {
  9.   constructor(
  10.     private eventEmitterService: EventEmitterService
  11.   ) { }
  12.   ngOnInit() {
  13.   }
  14.   firstComponentFunction(){
  15.     this.eventEmitterService.onFirstComponentButtonClick();
  16.   }
  17. }
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. <div>
  5.   <input type="button" value="Call First Component Function" (click)="firstComponentFunction()">
  6. </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. @Component({
  4.   selector: 'app-first',
  5.   templateUrl: './first.component.html',
  6.   styleUrls: ['./first.component.css']
  7. })
  8. export class FirstComponent implements OnInit {
  9.   constructor(
  10.     private eventEmitterService: EventEmitterService
  11.   ) { }
  12.   ngOnInit() {
  13.     if (this.eventEmitterService.subsVar==undefined) {
  14.       this.eventEmitterService.subsVar = this.eventEmitterService.
  15.       invokeFirstComponentFunction.subscribe((name:string) => {
  16.         this.firstFunction();
  17.       });
  18.     }
  19.   }
  20.   firstFunction() {
  21.     alert( 'Hello ' + '\nWelcome to C# Corner \nFunction in First Component');
  22.   }
  23. }
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. <div>
  5.   <input type=“text” #name>
  6.   <br>
  7.   <input type=“button” value=“Call Function” (click)=“firstFunction(name.value)”>
  8. </div>

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

second.component.html
  1. <p>
  2.   Second Component
  3. </p>
  4. <div>
  5.   <input type=“text” #name>
  6.   <br>
  7.   <input type=“button” value=“Call First Component Function” (click)=“firstComponentFunction(name.value)”>
  8. </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.