如果我有一个像这样的组件 @Component({selector: 'todo-cmp'})class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); // this f
@Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); // this fires an event } }
在另一个组件中,我通过DI获得它的副本,如:
... class SomeOtherClass(){ constructor(todoCmp:TodoCmp){ // how do I listen to ... } ...
如何在“SomeOtherClass”中手动添加事件侦听器,并侦听从DEPEmpmp的depenendcy注入实例触发的任何单击事件.
类似于todoCmp.addEventListener(‘complete’,function(e){});
也许?还是更好的ng2?
TX
肖恩.
首先,EventEmitter.next()一直是EventEmitter.emit(),因为alpha-45左右.其次,您正在寻找的方法是.subscribe()
class SomeOtherClass(){ constructor(todoCmp:TodoCmp){ todoCmp.complete.subscribe((result)=>{ //result == arg passed into emit() })) }
请注意,这些信息在the docs中很容易获得 – 您应该检查这些信息,因为EventEmitter比您习惯的事件监听器更强大.