Angular routerLink HostBinding

716 views Asked by At

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.

2

There are 2 answers

3
Aviad P. On

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>
0
SanderThunder On

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'])
}