Angular 2 assign click function using ternary operator

I would like to apply the click function:

setPage(page - 1)

But only if this condition matches:

page > 1

I thought I could do it this way, but it didn't work, any ideas?

<a (click)="{'setPage(page - 1)' : page > 1}">Previous</a></li>
+4
source share
3 answers

This should work:

<a (click)="page > 1 ? setPage(page - 1) : null">Previous</a></li>

similar example: http://plnkr.co/edit/ojO0GwQktneBuzKqKTwz?p=preview

+4
source

As mentioned in the comments:

Create a new method in your component, called for example onAnchorClick, and let it handle the logic.

public onAnchorClick(page: number) {
   if(page > 1) {
     this.setPage(page - 1);
     // some other stuff to do
   }
}

and tie it to your anchor

<a (click)="onAnchorClick(page)">Previous</a>
+3
source

<a (click)="page > 1 ? setPage(page - 1) : null">Previous</a></li>
+1

Source: https://habr.com/ru/post/1671352/


All Articles