[英]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:
这是父文件TS文件的一部分:
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: 这是子TS文件:
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: 和一个用于测试调用callParent方法的按钮:
<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. 当我单击按钮时,可以看到调用了callParent方法,但是没有触发应在父级(refreshList)中触发的方法。 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. 事件发射器仅影响组件的直接父对象,因此您需要将事件从app-add-operation扩展到app-operation,再扩展到app-car-detail。
See Emit event through nested components in Angular2 请参阅通过Angular2中的嵌套组件发出事件
Please add this function on your child component.you can refer this doc Component interaction 请将此功能添加到您的子组件上。您可以参考此文档组件交互
myEvent(event: any) {
console.log(event);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.