1

I have routerLink used in my template like this:

<li><a [routerLink]="[ 'discounts' ]">Wczesna oplata</a></li>

Is it possible to add a handler that would intercept that event and perform some action - like logging click - before routing takes place ?

2 Answers 2

3

Just add a click property:

<li ><a [routerLink]="[ 'discounts' ]" (click)="clicked()">Wczesna oplata</a></li>

Then in the component:

export class AppCom {
    clicked() {
        console.log('clicked');
    }
}
2

Well, what @John mentioned should work, but I would suggest you a generic solution for your problem. By adding directive component, you don't have to add you logging method everywhere:

import {Directive, Renderer, ElementRef, HostListener} from "@angular/core";

@Directive({
    selector: '[routerLink]'
})

export class FooClickTracker {

    constructor(elementRef: ElementRef, renderer: Renderer) {
        renderer.listen(elementRef.nativeElement, 'click', (event) => {
            console.log('clicked', event, elementRef.nativeElement);
        });
    }
}

You can verify that the listener will execute before routing takes place:

constructor(elementRef:ElementRef, renderer:Renderer) {
    renderer.listen(elementRef.nativeElement, 'click', (event) => {
        console.log('clicked', event, elementRef.nativeElement);
        this.sleep(5000)
    });
}

// we can mock waiting for small period of time http://stackoverflow.com/questions/16873323/javascript-sleep-wait-before-continuing
private sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.