11

here is my code below :

search.component.html

<button (click)="addMe()">Click</button>

search.component.ts

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

@Component({
   selector: 'search-component',
   templateUrl: './search.component.html'
})

export class SearchComponent {
   @Output() userUpdated = new EventEmitter();

   addMe() {
       this.userUpdated.emit('my data to emit');
   }
}

profile.component.html

<search-component (userUpdated)="handleUserUpdated($event)"></search-component>

profile.component.ts

handleUserUpdated(e) {
   console.log('e', e);
}
Chandru
  • 10,864
  • 6
  • 38
  • 53

1 Answers1

1

You should need to declare a type. Use @Output() userUpdated = new EventEmitter<string>(); if you want it to be a string or @Output() userUpdated = new EventEmitter<any>(); if it can be any type.

Also, you need to change your console log, try swapping to console.log("e-" + e)

mast3rd3mon
  • 8,229
  • 2
  • 22
  • 46
  • 1
    This is exactly what I would have suggested, not sure why you got down voted. – SeanOlson Dec 30 '17 at 19:35
  • 2
    Its because you apparently dont need to declare a type for the EventEmitter, even though intellisense will complain if you dont – mast3rd3mon Dec 31 '17 at 20:07
  • what you mean is not the typing itself, it is the correct EventEmitter initialization using the assignment and the type. Otherwise, it won't work. – seawave_23 Jul 18 '19 at 21:25
  • @Nadine can you please clarify what you mean? – mast3rd3mon Jul 19 '19 at 10:15
  • check the Angular docu for that. It needs to be initialized. The answer has the type declaration in the wrong place: @Output() open: EventEmitter = new EventEmitter(); – seawave_23 Jul 21 '19 at 19:46
  • @Nadine this was originally for angular 4 iirc, and as the docs will not be for v7/8, thing will probabably have changed – mast3rd3mon Jul 22 '19 at 08:57
  • https://angular.io/api/core/EventEmitter those are the up to date docs. But your IDE should provide a syntax check and inform you anyways... The key fact is that an EventEmitter needs to be initialized. – seawave_23 Jul 22 '19 at 09:55
  • @Nadine that is exactly what this answer does, or atleast did at the time of writing – mast3rd3mon Jul 23 '19 at 13:28