Search code examples
javascriptangulartypescripteventemitter

Angular - emitted event doesn't get through to parent component


I'm trying to emit an event from a child component to a parent component. Here is part of the parent file TS file:

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

@Component({
  selector: 'app-car-detail',
  templateUrl: './car-detail.component.html',
  styleUrls: ['./car-detail.component.css'],
})
export class CarDetailComponent implements OnInit {
  constructor() { }

  ngOnInit() {
    this.getCarDetail(this.route.snapshot.params['id']);
  }

  refreshList(event){
    console.log("Parent called");
  }
}

And part of the template that concerns the emitter

<app-operations (myEvent)="refreshList($event)"></app-operations>

Here is the child TS file:

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


@Component({
  selector: 'app-add-operation',
  templateUrl: './add-operation.component.html',
  styleUrls: ['./add-operation.component.css']
})
export class AddOperationComponent implements OnInit {


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

  constructor() { }

  ngOnInit() {
  }

  callParent() {
    console.log('callparentmethod');
    this.myEvent.emit('eventDesc');
  }

}

and a button to test call the callParent method:

<button (click)="callParent()">call</button>

When I click the button, I can see that the callParent method is triggered, but the method that should be triggered in the parent (refreshList) isn't. I looked at multiple examples and don't understand why this isn't working.


Solution

  • Your view is referencing the wrong component. Try this:

    <app-add-operation (myEvent)="refreshList($event)"></app-add-operation>