admin管理员组

文章数量:1208153

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>

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>
Share Improve this question asked Mar 3, 2017 at 11:33 Andrew HowardAndrew Howard 3,0726 gold badges40 silver badges71 bronze badges 8
  • 1 Have you tried giving the anchor it's own click method which handles this logic? It would be cleaner. – Kallum Tanton 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 – cyr_x 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. – Kallum Tanton 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. – Kallum Tanton Commented Mar 3, 2017 at 11:37
  • It did mean the same as you ;) just forgot to change the method name. – cyr_x Commented Mar 3, 2017 at 11:38
 |  Show 3 more comments

3 Answers 3

Reset to default 14

This should work:

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

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

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>

You can do this

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

本文标签: javascriptAngular 2 assign a click function using a ternary operatorStack Overflow