Angular:EventEmitter的活动未能通过.subscribe成功收到

时间:2017-08-30 15:41:03

标签: javascript angular typescript rxjs eventemitter

我尝试通过引用传递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> 未被调用。

应该导致问题的原因是什么?

1 个答案:

答案 0 :(得分:2)

在发出事件后,Angular运行会更改NgDNDirective的检测。

因此,请手动运行更改检测:

const view = this.container.createEmbeddedView(this.template, {index: i, ev: ref});
view.detectChanges();

<强> Plunker Example

或使用ReplaySubject代替EventEmitter

<强> Plunker Example