Answers for "ionic adding [routerLink] as a part of dynamic html"

1

ionic adding [routerLink] as a part of dynamic html

routerLink cannot be added after the content is already rendered but you can still achieve the desired result:

Create a href with dynamic data and give it a class:

`<a class="routerlink" href="${someDynamicUrl}">${someDynamicValue}</a>`
Add a HostListener to app.component that listens for the click and uses the router to navigate

@HostListener('document:click', ['$event'])
public handleClick(event: Event): void {
 if (event.target instanceof HTMLAnchorElement) {
   const element = event.target as HTMLAnchorElement;
   if (element.className === 'routerlink') {
     event.preventDefault();
     const route = element?.getAttribute('href');
     if (route) {
       this.router.navigate([`/${route}`]);
     }
   }
 }
}
Posted by: Guest on July-08-2021

Code answers related to "ionic adding [routerLink] as a part of dynamic html"

Browse Popular Code Answers by Language