0

I want to add a routerLink to the Host Element in an Angular Component like this:

@HostBinding('routerLink') routerLink = '/my-route'

But when I click the component, it wont navigate to the specified route. What am I doing wrong? Is this even possible with Angular 11?

EDIT: I also tried the old way of host binding (that is not recommended by tslint: Use @HostBinding or @HostListener rather than the host metadata property (https://angular.io/styleguide#style-06-03) (no-host-metadata-property)tslint(1):

host: {
  '[routerLink]': '[\'/my-route\']'
},

There is no router navigation following this either.

  • Does this answer your question? [Angular2 host: { '\[routerLink\]': '/foo' }](https://stackoverflow.com/questions/36171195/angular2-host-routerlink-foo) – Kordrad Aug 11 '21 at 08:55
  • @Kordrad thanks for your reply! I've tried it this way with the same results, unfortunately. – SanderThunder Aug 11 '21 at 12:09

2 Answers2

0

You are having a confusion of terms - routerLink is a directive which has a property (of the same name) - however, the way you are using it, your expectation is that the component itself has a property called routerLink - but it doesn't.

The proper way to use routerLink is to add it as an Angular directive to an element or component in an Angular template:

<some-component routerLink="..."></some-component>
Aviad P.
  • 32,036
  • 14
  • 103
  • 124
  • Thanks for your reply. So there is no way to do what I'm trying to achieve then? I specifically didn't want to put the routerLink on the tag because then I would have to add it everywhere I use my component. I wanted it to get added on the host element of my component so I wouldn't have to add another div in my components html. – SanderThunder Aug 11 '21 at 12:02
  • You could listen on the click event, see @user1313805 's answer – Aviad P. Aug 11 '21 at 13:07
  • Oh that's your own answer :) - well that's a good way – Aviad P. Aug 11 '21 at 13:19
0

The only way I could get a navigation working programmatically on the component itself so far is like this:

@HostListener('click')
onClick($event): void {
  this.router.navigate(['/my-route'])
}