Angular 2 rounterLink添加处理程序

时间:2016-10-08 02:07:27

标签: angular routing handler routerlink

我的模板中使用了routerLink,如下所示:

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

是否有可能在路由发生之前添加一个拦截该事件并执行某些操作的处理程序(如日志记录点击)?

2 个答案:

答案 0 :(得分:3)

只需添加点击属性:

#include<iostream>
using namespace std;
int main()
{
int a[10];
int reper=0,word=0,flage=0,number[10]={
    0
};
//Getting Input From User
for (int i = 0; i <=9; i++)
{
    cout<<"Enter The Value For "<<i<<" Index"<<endl;
    cin>>a[i];
}
//Checking The Duplicates Numbers
for (int i = 0; i <= 9; i++)
{
    reper=0;
    flage=0;

    for (int j = 0; j <=9; j++)
    {
        if (a[i]==a[j])
        {
            if (i!=j)
            {
                reper++;
            }
        }
    }
    number[i]=a[i];
    for (int k = 0; k <=9; k++)
    {
        if (i!=k)
        {
            if(number[i]==number[k])
            {
            flage=1;
            break;
            }
        }
    }
    //If There Are Duplicates Then Prints That Numebr, How Many Times It Repeated And Total Occurance Of That Number In The Array
    if (reper!=0&&flage==0)
    {
        cout<<"Repeated Number Of The Array Is  : "<<a[i]<<" ";
        cout<<"And This Number Repeated "<<reper<<" Times "<<"And Total Occurance Of This Number is : "<<reper+1<<endl;
        word=a[i];
    }
}
//If There Is Nothing Any Duplicate In The Array Then Simply Prints This Message On Console
if (reper==0&&word==0)
{
    cout<<"There Is Nothing Any Repeated Number Of This Array: "<<endl;
}
system("Pause");
return 0;
}

然后在组件中:

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

答案 1 :(得分:2)

嗯,@ John所提到的应该有用,但我会建议你为你的问题找到一个通用的解决方案。通过添加指令组件,您无需在任何地方添加日志记录方法:

ROWS

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

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