11

I would like to apply a click function:

setPage(page - 1)

But only if this condition matches:

page > 1

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

<a (click)="{'setPage(page - 1)' : page > 1}">Previous</a></li>
8
  • 1
    Have you tried giving the anchor it's own click method which handles this logic? It would be cleaner. Commented Mar 3, 2017 at 11:35
  • 2
    Just assign onLinkClick(page) to it and let the method handle it if(page > 1) ...do something Commented Mar 3, 2017 at 11:36
  • However if you are dead set on this mechanism it would be something like (click)="page > 1 ? setPage(page - 1) : void", assuming that setPage has a void return. Commented Mar 3, 2017 at 11:36
  • 1
    @cyrix That method would mean that the setPage method is coupled to the anchor - it's likely that other things will call this method and the page > 1 logic will not be applicable. Commented Mar 3, 2017 at 11:37
  • It did mean the same as you ;) just forgot to change the method name. Commented Mar 3, 2017 at 11:38

3 Answers 3

14

This should work:

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

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

Sign up to request clarification or add additional context in comments.

Comments

4

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 bind it to your Anchor

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

1 Comment

Thanks for your help on this. I went ahead with Echonax answer because I have many other operators going on in the same page and preferred keeping the logic there rather than having some logic in the html file ans some logic in the method. Many thanks :)
1

You can do this

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

1 Comment

Thanks for your help Rahul. Echonax got in there just a few seconds before you but still thanks for your help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.