2

I don't think it is possible but I prefer to ask (just in case): Is it possible to do something like :

@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) {
    ...
  }

}

And call it like that :

<div [appTag]="myTagParam">Watch for click on this div</div>
<div [appTag]="myTagParam" [tagTriggerEvent]="mouseenter">Watch for mouseenter on this div</div>
Anne Lacan
  • 753
  • 1
  • 5
  • 8

1 Answers1

1

That's not supported. These decorators are evaluated at build time.

You can use

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);});
}

See also Dynamically add event listener in Angular 2

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567