Search code examples
angulareventemitter

Angular 7 problem with listening event on parent component


I am new to angular and I am struggling with receiving events in parent component. I know that this problem has been discussed before, but somehow none of the tips or the tutorials I have read could help me understand what I am doing wrong...

In my child component.ts I do something like this:

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  template: `<button class='btn btn-primary' (click)="nameChanged()">Click me</button> `
})
export class TestComponent implements OnInit {

    @Output() onTestEvent = new EventEmitter<string>()
    public text: string = "blah";

  constructor() { }

  ngOnInit() {
  }

  nameChanged() {
    console.log('Sending test event!');
    this.onTestEvent.emit(this.text)
  }
}

On my parent component html file I do something like this:

  <app-test>
    (onTestEvent)="handleTestEvent($event)"
  </app-test>

On my parent component ts file I do something like this:

  handleTestEvent(text: string) {
    console.log('handling test event....');
  }

I can see that the nameChanged function is called when I press the button, but I don't receive the event in the parent component for some reason that is beyond me...


Solution

  • has to go inside the tag...

    <app-test (onTestEvent)="handleTestEvent($event)">
    
    </app-test>