Add element with RouterLink dynamically

后端 未结 3 2048
悲&欢浪女
悲&欢浪女 2020-12-10 15:20

When i put an anchor element in someweher in a angular 2 Component like this,

Static Link
         


        
3条回答
  •  無奈伤痛
    2020-12-10 16:06

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

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

      `${someDynamicValue}`
      
    2. 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}`]);
           }
         }
       }
      

      }

提交回复
热议问题