Angular2 - 是否可以为HostListener使用变量字符串?

时间:2016-11-10 10:49:16

标签: html events angular angular2-directives

我不认为这是可能的,但我更愿意问(以防万一):是否可以这样做:

@Directive({
  selector: '[appTag]'
})
export class TagDirective {
  @Input() appTag: TagEvent;

  private _tagTriggerEvent = 'click';
  @Input() set tagTriggerEvent(triggerEvent: string) {
    this._tagTriggerEvent = triggerEvent || this._tagTriggerEvent;
  }

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener(this._tagTriggerEvent) onTriggerEvent() {
    if (this.appTag) {
      this.sendTag(this.appTag);
    }
  }

  sendTag(tagParam: TagEvent) {
    ...
  }

}

并称之为:

<div [appTag]="myTagParam">Watch for click on this div</div>
<div [appTag]="myTagParam" [tagTriggerEvent]="mouseenter">Watch for mouseenter on this div</div>

1 个答案:

答案 0 :(得分:0)

不支持。这些装饰器在构建时进行评估。

您可以使用

constructor(private renderer:Renderer, private elementRef:ElementRef) {}

private tagTriggerEventRegistration:Function;
@Input() set tagTriggerEvent(event:string) {
  if(this.tagTriggerEventRegistration) {
    this.tagTriggerEventRegistration(); // cancel previous listener
  }
  this.tagTriggerEventRegistration = this.renderer.listen(this.elementRef.nativeElement, event, (event) => { onTriggerEvent(e);});
}

另见Dynamically add event listener in Angular 2