Last updated on February 6, 2020
This post helps you to aware the simple idea behind preventing default action of anchor HTML element.
Why in Angular?
Yes, in JavaScript it was very straight forward to attain this behavior whereas in an angular application which is created with angular-cli
will throw an error when certain combination if we carried out. We will see that in more detailed below.
Problem?
In certain cases, we would end up using anchor tag for designing an element such as dropdown or accordion
in HTML. When we click on accordion or dropdown element (anchor tag) if our application uses nested/child routing this would resets to default route which is not the expected behavior.
The expected behavior would be simply just to expand/collapse the HTML container element, usually we write <a href="#" class="collapse" (click)="toggle()">Toggle</a>
Solution?
We have a certain combination to solve this problem just by having return false;
inside toggle() method
which would work in JavaScript app not in angular where we will get an error.
On more thing is event.preventDefault();
to keep inside toggle() method
this also don’t work out.
Finally, working solution is ,
// html
<a href="javascript: void(0)" class="collapse" (click)="toggle()">Toggle</a>
// typescript-component class
export class AppComponent {
constructor() {}
toggle(event) {
event.stopPropagation();
// logic for accordion
}
}
Here href="javascript: void(0)"
represents simply bind the event handler for anchor element but not redirecting event.stopPropagation()
will not propagate the anchor action to the parent DOM tree thus default action of anchor tag is prevented.