[英]How do I detect a custom event in Angular 2 without using a template?
I have an Angular 2 project where I am dynamically generating child components and I want to listen to a custom event that is dispatched by that component. 我有一个Angular 2项目,我在其中动态生成子组件,并且我想听由该组件调度的自定义事件。
This is my parent component that generates the component and listens for events 这是我的父组件,它生成该组件并侦听事件
var cmpRef: ComponentRef<any>;
let factory = this.componentFactoryResolver.resolveComponentFactory(type);
cmpRef = this.target.createComponent(factory);
// PROPERLY DETECTS EVENT
cmpRef.instance.self.nativeElement.addEventListener('click',this.onEventFired);
// DOESN'T DETECT EVENT
cmpRef.instance.self.nativeElement.addEventListener('isLoaded',this.onEventFired);
// call this method to fire the event
(cmpRef.instance as ChildComponent).load();
And this is my ChildComponent 这是我的ChildComponent
import { Component, OnInit,ChangeDetectorRef, Output,EventEmitter,ElementRef } from '@angular/core';
@Component({
selector: 'app-child',
template: ' <p>child component- click on text to fire event!</p>'
})
export class ChildComponent implements OnInit, AfterViewInit {
@Output('isLoaded') isLoaded:EventEmitter<boolean> = new EventEmitter<boolean>();
constructor(public self:ElementRef)
{
console.log('ChildComponent Created')
}
public load()
{
console.log('load method called.... dispatching event')
this.isLoaded.next(true);
}
}
I need to be able to listen to the events that are being dispatched but for my purposes, I cannot use the template and want to listen directly from my typescript. 我需要能够侦听正在调度的事件,但是出于我的目的,我无法使用模板,而是希望直接从我的打字稿中侦听。 I have successfully done this with a "click" event but my custom events get dispatched but never gets detected. 我已经通过“ click”事件成功完成了此操作,但是我的自定义事件被调度了,但从未被检测到。
I have attached a plunker to show my use case 我已经附上了一个插件来展示我的用例
https://plnkr.co/edit/GGqhRu8pT6Ymz2Bg7oSE?p=preview https://plnkr.co/edit/GGqhRu8pT6Ymz2Bg7oSE?p=preview
That's not how it's supposed to work, if you want to subscribe to your isLoaded
event just cast that component created by the factory and subscribe to isLoaded
event. 如果您要订阅isLoaded
事件,只需将工厂创建的组件isLoaded
并订阅isLoaded
事件,这不是应该的工作方式。
Just change your: 只需更改:
// DOESN'T DETECT EVENT
cmpRef.instance.self.nativeElement.addEventListener('isLoaded',this.onEventFired);
For: 对于:
// DOESN'T DETECT EVENT
(<ChildComponent>cmpRef.instance).isLoaded.subscribe(() => {
console.log("Has been loaded");
});
First case worked because that is a native event of the host. 第一种情况有效,因为这是主机的本地事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.