简体   繁体   中英

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.

Your view is referencing the wrong component. Try this:

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

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

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

 myEvent(event: any) {
     console.log(event);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM