Search code examples
htmlangulartypescriptcomponentseventemitter

Angular: How to send string values to another component using EventEmitter?


I have a parent component and a child component, I want to send 2 values from the child component via EventEmitter to the parent component as I want to use the printMessages() function there.

I have a click event on the child component which emits 2 string values, but I'm unsure how to connect the emit event to the parent component and for the printMessages() function to run. How can the parent component read these values into the "printMessages()" function and for that function to run after the values have reached it? As you can see, I currently have no HTML in the parent component, perhaps I need to do something there?

Parent Component:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'parent-component',
      template: ``,
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent {
    
      constructor() { }
    
      // Function in which I want to send values from the child component. 
      printMessages(string1: string, string2: string) { 
    
        console.log(string1, string2);
    }

Child Component:

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `
      <button (click)="sendStrings()">Send Strings</button>
  `,
  styleUrls: ['./child.component.css']
})

export class ChildComponent {

  @Output() message = new EventEmitter();

  constructor() { }

sendStrings(){
  this.message.emit({string1:"Hello", string2:"World!"});
    }
}

Solution

  • You need to react on the child components event within the template and call the method.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'parent-component',
      template: `<child-component (onMessage)="printMessages(e)"></child-component>`,
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent {
    
      constructor() { }
    
      printMessages(event) { 
        // strings are included in event object
      }
    }