我尝试通过引用传递EventEmitter对象并按照描述调用NgLoopDirective
来尝试在EV
的{{1}}方法中处理来自NgDNDirective
的事件在下面的代码中:
.subscribe()
这是使用过的HTML代码:
import { Directive, Input, ElementRef, Renderer2, EventEmitter } from '@angular/core';
@Directive({
selector: '[ngDN]'
})
export class NgDNDirective {
private dn: number = -1
private ev: EventEmitter<void>;
@Input() set ngDN(dn: number) {
this.dn = dn
}
@Input() set EV(ref: {ev: EventEmitter<void>}) {
console.log('waiting for ev')
ref.ev.subscribe(() => {
console.log('data-num:', this.dn)
this.renderer.setAttribute(this.elRef, 'data-num', this.dn.toString())
})
}
constructor(private elRef: ElementRef,
private renderer: Renderer2) {}
}
@Directive({
selector: '[ngLoop]'
})
export class NgLoopDirective {
@Input() set ngLoop(iter_count: number) {
this.container.clear()
for (let i=0; i<iter_count; i++) {
let ev: EventEmitter<void> = new EventEmitter<void>()
let ref = {ev: ev}
this.container.createEmbeddedView(this.template, {index: i, ev: ref})
ev.emit()
}
}
constructor(private template: TemplateRef<any>,
private container: ViewContainerRef) {}
}
当我在控制台下调试代码时 - 我只显示此消息:
等待ev
意味着事件未成功处理,因为<ng-template [ngLoop]="10" let-i="index" let-ref="ev">
<a href="#" [ngDN]="i" [EV]="ref"></a>
</ng-template>
未被调用。
应该导致问题的原因是什么?
答案 0 :(得分:2)
在发出事件后,Angular运行会更改NgDNDirective
的检测。
因此,请手动运行更改检测:
const view = this.container.createEmbeddedView(this.template, {index: i, ev: ref});
view.detectChanges();
<强> Plunker Example 强>
或使用ReplaySubject
代替EventEmitter
<强> Plunker Example 强>