SanderThunder
SanderThunder

Reputation: 73

Angular routerLink HostBinding

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.

Upvotes: 1

Views: 929

Answers (2)

SanderThunder
SanderThunder

Reputation: 73

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

Upvotes: 0

Aviad P.
Aviad P.

Reputation: 32670

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>

Upvotes: 0

Related Questions