I am trying to attach click event to anchor tags (coming from ajax) and block the default redirection. How can I do it in angular ?
<ul>
<li><a href="/abc"><p>abc</p></a></li>
<li><a href="/abc1"><p>abc1</p></a></li>
<li><a href="/abc2"><p>abc2</p></a></li>
<li><a href="/abc3"><p>abc3</p></a></li>
</ul>
In ts file:
constructor(elementRef: ElementRef, renderer: Renderer) {
this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
event.preventDefault();
let target = event.target || event.srcElement || event.currentTarget;
console.log(target);
});
}
This will attach event to all elements, how can I limit this to anchor tag only ?
All helps appreciated.
You can use routerLink
(which is an alternative of href
for angular 2+) with click event as below to prevent from page reloading
<a [routerLink]="" (click)="onGoToPage2()">Go to page</a>