0

I'm working with angular-cli and I have a menu structured as follow(ul->li guided):

<ul class="sub-menu">
    <li class="nav-item  ">
        <a routerLink="/logistica/contenedores" class="nav-link ">
            <span class="title">Adicionar</span>
        </a>
    </li>
</ul>

the problem is when I'm using routerlink. I have a javascript that manage the events on menu but my question is If I could override that javascript with a directive or something else.

The routerlink works perfectly for tags outside the menu structure. Also I implemented a directive but is not catching the event not even pass for console.log:

import {AfterViewInit, Directive, ElementRef, Input, HostBinding, HostListener} from '@angular/core';

@Directive({
  selector: '[appHrefPreventDefault]',
  // host: {'(click)': 'preventDefault($event)'},
})
export class HrefPreventDefaultDirective {
  @Input() href: string;

  @HostBinding('onclick') preventDefault2(event) {
    if (this.href.length === 0 || this.href === '#') {
      event.preventDefault();
    }
    console.log('href directive');
  }

  @HostListener('onclick') preventDefault(event) {
    if (this.href.length === 0 || this.href === '#') {
      event.preventDefault();
    }
    console.log('href directive');
  }

  constructor(private el: ElementRef) {

  }

}

Thanks in advance!

Juan I. Morales Pestana
  • 1,057
  • 1
  • 10
  • 34
  • In your example, I think the problem is that you didn't add the `apphrefPreventDefault` attribute to the `routerLink` – James Mar 17 '18 at 00:30
  • @Juan - "the problem is when I'm using routerlink" - what exactly do you mean by the problem? What exactly does your code do that you do not anticipate? – Alexander Leonov Mar 17 '18 at 01:41
  • @AlexanderLeonov is just a menu and should render the component asociated with the route defined in routerLink attr. – Juan I. Morales Pestana Mar 19 '18 at 12:17
  • Solved!! I just moved the menu definition from index.html to app.component.html and all works fine. I did not need to use the directive. Does some have an explanation? – Juan I. Morales Pestana Mar 19 '18 at 12:21

0 Answers0