Search code examples
angulartypescriptangular-ng-if

How to assign values in ngIf


I'm new to Angular. I'm learning directives. I'm using pTooltip from primeng. But I want to display text in pTooltip according to a condition.

Let's take example of Stack Overflow itself. You cannot upvote an answer twice. User should get msg1 if he has not upvoted that particular article otherwise he should get msg2. Where:

msg1="I found this article very useffeul.";
msg2="You've already upvoted this article";

Here is my code:

article.component.html

<button 
  class="btn btn-success"
  *ngIf="allowUpvote ? pTooltip={{msg1}} : pTooltip={{msg2}}
  [disabled]="!allowUpvote">
  UPVOTE
</button>

article.component.ts

...
allowUpvote=true;
msg1="I found this article very useffeul.";
msg2="You've already upvoted this article";
...

ngOnInit() {
  for(var i=0;i<5;i++) {
    if(this.currentLoggedInUserId==this.articleDetails.upvotersList[i]) {
      this.allowUpvote=false; //It will be set false if the user is there in the upvoters list
    }
  }
});

But I'm getting this error:

Parser Error: Bindings cannot contain assignments at column 24 in [allowUpvote ? pTooltip={{msg1}} : pTooltip={{msg2}}]

Please give me some directions.


Solution

  • Try this

    [pTooltip] = "allowUpvote ? msg1 : msg2"
    

    Using [], the interpretor know to read and execute code between ""

    Updated, better explained by Plochie

    When you say pTooltip="value" that means use value provided in "" as parameter for pTooltip. Here you have not binded the value from component, you have just given the constant. To have databinding you need []. Now after [], it means that bind whatever written in "" with the pTooltip and hence it will execute the code inside "" and the output for that statement then will be treated as input for pTooltip