html - Angular2 - Is it possible to use variable string for HostListener? -
i don't think possible prefer ask (just in case): possible :
@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 :
<div [apptag]="mytagparam">watch click on div</div> <div [apptag]="mytagparam" [tagtriggerevent]="mouseenter">watch mouseenter on div</div>
that's not supported. these decorators evaluated @ 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);}); }
Comments
Post a Comment