从子组件到父组件的Angular 5 EventEmitter发出未定义 [英] Angular 5 EventEmitter from child to parent component emits undefined
问题描述
我正在尝试将string
从子组件发送到其父组件.
I am trying to send a string
from a child component to his parent component.
这是孩子:
//imports...
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
providers: [ChildService]
})
export class DataTableComponent implements OnInit {
constructor(private http: HttpClient, private childService : ChildService) {}
myMap = new Map<string, ISomeInterface>();
currentSelection: string;
@Output() sendDataEvent = new EventEmitter<string>();
sendData() {
console.log("sending this data: " + this.myMap.get(this.currentSelection).name);
this.sendDataEvent.emit(this.myMap.get(this.currentSelection).name);
}
}
这是父母:
html->
<d-table (sendDataEvent)="receiveBusinessCycle(event)"></d-table>
打字稿->
//imports...
@Component({
selector: 'parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css'],
providers: [ParentService]
})
export class MyParentComponent {
totoName: string;
constructor(private parentService : ParentService) { }
receiveBusinessCycle($event) {
console.log($event); //shows in console 'undefined'
console.log($event as string);
this.totoName = $event;
}
}
问题是,当接收父组件中的数据时,我得到一个 undefined 事件,这里是控制台日志:
The issue is that I am getting an undefined event when receiving the data in the parent component, here console logs :
sending this data: 201808
main.bundle.js:2328 undefined
main.bundle.js:2329 undefined
关于这个问题有什么想法吗?
Any ideas on the issue?
推荐答案
您应该在此处使用$event
:
<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>
我以前也遇到过类似的情况,显然,它只与$event
一起使用,因为它是捕获事件对象的保留关键字.
I've faced a similar situation before and apparently, it seems to only work with $event
as it is a reserved keyword to grab the event object.
显然,Angular仅在$event
中提供了相应的DOM事件对象.这就是为什么不能将任何其他变量作为参数传递的原因.您可以在此处了解更多信息
Apparent, Angular provides a corresponding DOM event object in the $event
only. That's why passing in any other variable as an argument won't work. You can read more about it here.
Angular在使用本地HTML元素时也认为这是一种可疑的做法,因为它打破了模板和组件之间关注点的分离. Angular建议改为使用模板变量.在此处中了解详情.
Angular also considers this as a dubious practice when working with native HTML Elements as it breaks the separation of concerns between the template and the component. Angular recommends the use of Template Variables instead. Read more about it here.
这篇关于从子组件到父组件的Angular 5 EventEmitter发出未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!