-1

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.

Matt
  • 556
  • 8
  • 31
  • 2
    I see that the child component's selector is `app-add-operation` but you're providing `app-operations` in the template. Is this an issue or is something missing in the question? – Zircon May 08 '18 at 15:35
  • This was the issue. I messed up because car-detail is the parent of operations which is the parent of add-operation and got mixed up, my bad, stupid mistake. – Matt May 08 '18 at 15:39
  • 2
    I recommend deleting this question since it's not very useful for future readers. – Zircon May 08 '18 at 15:42

3 Answers3

5

Your view is referencing the wrong component. Try this:

<app-add-operation (myEvent)="refreshList($event)"></app-add-operation>
bc1105
  • 1,270
  • 8
  • 8
2

Event Emitters only affects the direct parent of the component, so you'll need to bubble the event from app-add-operation to app-operation and then app-car-detail.

See Emit event through nested components in Angular2

Joshua Chan
  • 1,797
  • 8
  • 16
0

Please add this function on your child component.you can refer this doc Component interaction

 myEvent(event: any) {
     console.log(event);
  }
Sharma Vikram
  • 2,440
  • 6
  • 23
  • 46