VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-pass-two-parameters-to-eventemitter-in-angular-9/

⇱ How to pass two parameters to EventEmitter in Angular 9 ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to pass two parameters to EventEmitter in Angular 9 ?

Last Updated : 5 Jun, 2020

In Angular, we can transmit the data in both directions i.e. inside: to the child component and outside: to the parent component. For sending data to the child component, we use property binding and for the latter we use EventEmitter.

In this article, we will talk about the EventEmitter directive and how can we pass 2 parameters in it.

Let's take a look at EventEmitter source code:

It is clearly visible that in the emit method only one parameter of type T can be passed, so we cannot pass two parameters directly into it. Instead, we can make an object containing all the parameters and pass the object as a single entity.

Approach:

  • EventEmitter allows us to emit any type of object, so we will take advantage of it.
  • For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method.
  • To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.

Syntax:

@Output() sendobject = new EventEmitter<any>();

this.sendobject.emit({stringval, numval, ...});

Example: We will create two properties in child component and receive them in parent component by using EventEmitter.

Code for the child component: Code for the parent component:

Output:

Successfully received both age and name from child component in the parent component.

  • Before receiving name and age:
    👁 Image
    Before receiving data
  • Name and age in the parent component is updated after receiving it from child component.
    👁 Image
    After receiving data
Comment
Article Tags:

Explore