Dallas Caley
Dallas Caley

Reputation: 5888

How to add parameter to Angular click function in ngFor loop

This seems simple but it doesn't work. I am making pagination for a list of things. I have a pagination object that is defined as such:

in my models.ts:

export interface PageLink {
    displayText: string;
    pageNumber: number;
    status: string;
}

in my controller:

pageLinks: Array<PageLink>;

in my html:

<a *ngFor="let link of pageLinks" (click)="togglePage('test')" class="{{link.status}}">{{link.displayText}}</a>

This all works without blowing up, however my desire was to have the pageNumber parameter of the PageLink object put inside of the togglePage() function. Doing this however:

<a *ngFor="let link of pageLinks" (click)="togglePage('{{link.pageNumber}}')" class="{{link.status}}">{{link.displayText}}</a>

Blows up. When i do this i get very many lines of error in my console however the gist of the error is this:

Got interpolation ({{}}) where expression was expected

Why does this happen, and how can i avoid it?

Note: This is Angular 5

Upvotes: 1

Views: 5500

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

No need to use interpolation. Whatever you have been passed to inside event attribute, it is going to evaluate against component context directly. The value of pageNumber would passed to togglePage function directly.

(click)="togglePage(link.pageNumber)"

Upvotes: 4

santosh singh
santosh singh

Reputation: 28692

This will work.No need to use interpolation

  <a *ngFor="let link of pageLinks" 
(click)="togglePage(link.pageNumber)" class="{{link.status}}">{{link.displayText}}</a>

Upvotes: 1

Related Questions