Jonathan Clark
Jonathan Clark

Reputation: 20558

How to use dynamic router links with method

I am building an Angular 7 app. In this app I got a set of links. When the page loads the getRouterURL fires for each of the links (and everytime I click one of the links all fire the method. Is this the correct behaviour? It feels like a waste of memory?

<a [routerLink]="getRouterURL('normal')">Link</a>
<a [routerLink]="getRouterURL('normal')">Link 2</a>
<a [routerLink]="getRouterURL('page')">Link 3</a>
<a [routerLink]="getRouterURL('page')">Link 4</a>

The method looks like this.

getRouterURL(type) {
  console.log('Method fired');
  if (type === 'normal') {
    return 'normal' + this.proposalId + '/' + model.id;
  } else {
    return 'pages' + this.proposalId + '/' + model.id;
  }

}

Am I doing this correctly?

Upvotes: 1

Views: 215

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71971

This is normal behaviour. Angular has no way of knowing if that binding has changed. It can only know it by executing the function again. That's why it's usually better to limit the amount of function call bindings from inside your template. You can either solve this by using an @Input() which somehow sets the data, or even better, by using a pure @Pipe

Upvotes: 1

Related Questions