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 ?

4

2 回答 2

3

只需添加一个点击属性:

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

然后在组件中:

export class AppCom {
    clicked() {
        console.log('clicked');
    }
}
于 2016-10-08T06:18:13.820 回答
2

好吧,@John 提到的应该可行,但我建议你为你的问题提供一个通用的解决方案。通过添加指令组件,您不必在任何地方添加您的日志记录方法:

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

您可以验证侦听器将在路由发生之前执行:

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;
        }
    }
}
于 2016-10-08T09:42:48.483 回答