Davvit Davvit - 3 years ago 283
TypeScript Question

Passing parameter to angular directive in typescript

I have the following directive. I am trying to pass the class name that needs to be toggled when the link/button is clicked. I keep getting undefined in debug console. HostListener takes array of args - i guess i am not sure how to pass them and cant seem to find example of it.

selector: '[appSidebarToggler]'
export class SidebarToggleDirective {

constructor(public elementRef: ElementRef) {

@HostListener('click', ['$event', '$tobeToggledClassName'])

toggleOpen($event: any, $tobeToggledClassName: any) {
console.log("class to be toggled is - >" + $tobeToggledClassName);
console.log("ref - >" + this.elementRef);


and i am using it like this in my component :

<a class="" href="#" sidebarToggler tobeToggledClassName="sideMenu">&#9776;</a>


Answer Source

You can pass it like:

@HostListener('click', ['$event', '$event.target.getAttribute("tobeToggledClassName")'])

Example 1

or use injected ElementRef


Example 2

or inject @Attribute in contstructor of your directive:

constructor(...@Attribute('tobeToggledClassName') private tobeToggledClassName: string) {}

Example 3

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download