2

I've created a directive

import {
  Directive, AfterContentInit, Output, EventEmitter
} from '@angular/core';

@Directive({ selector: '[attached]' })
export class AttachDirective implements AfterContentInit {

  @Output("attached")
  private ee: EventEmitter<AttachDirective> = new EventEmitter();

  ngAfterContentInit() { setTimeout(() => this.ee.next(this)); }

}

to define a custom event that should fire when a DOM element to which it is bound gets "attached" to the view. So for example <input (attached)="do something" ... does something as soon as the <input> shows up on the page.

The event fires well, my problem is however that when I'd like to access its target like <input (attached)="$event.target.something = 'anything'" I get an error such as

Cannot set property 'something' of undefined

How to upgrade my directive so I can access the target of the event?

4

2 回答 2

1

当您使用输出发出组件实例时,没有 $event.target 。但是,您可以使用发出组件的 elementRefthis.ee.next(this.elementRef)

在构造函数中注入 elementRef:

constructor(elementRef: ElementRef) { }

于 2018-05-26T01:33:05.980 回答
1

要将元素访问为$event.target,请定义一个target属性,该属性返回应用该指令的 HTML 元素:

@Output("attached") private ev: EventEmitter<AttachDirective> = new EventEmitter();

constructor(private elementRef: ElementRef) { }

public get target(): HTMLElement {
  return this.elementRef.nativeElement as HTMLElement;
}

ngAfterContentInit() {
  this.ev.next(this);
}
<input type="text" (attached)="$event.target.disabled = true" >

请参阅此 stackblitz以获取演示。

于 2018-05-26T03:07:07.073 回答