【问题标题】:How to assign values in ngIf如何在 ngIf 中赋值
【发布时间】:2019-12-25 18:11:30
【问题描述】:

我是 Angular 的新手。我正在学习指令。我正在使用来自primengpTooltip。但是我想根据条件在pTooltip中显示文本。

让我们以 Stack Overflow 本身为例。您不能两次投票赞成一个答案。如果用户没有为该特定文章投票,他应该得到 msg1,否则他应该得到 msg2。地点:

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

这是我的代码:

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
    }
  }
});

但是我收到了这个错误:

解析器错误:绑定不能包含 [allowUpvote 中的第 24 列的赋值? pTooltip={{msg1}} : pTooltip={{msg2}}]

请给我一些指示。

【问题讨论】:

    标签: angular typescript angular-ng-if


    【解决方案1】:

    试试这个

    [pTooltip] = "allowUpvote ? msg1 : msg2"
    

    使用[],解释器知道在“”之间读取和执行代码

    更新Plochie更好地解释

    当您说 pTooltip="value" 时,表示使用 "" 中提供的值作为 pTooltip 的参数。在这里,您没有绑定来自组件的值,您只是给出了常量。要进行数据绑定,您需要 []。现在在[]之后,这意味着将“”中写入的任何内容与pTooltip绑定,因此它将执行“”中的代码,然后该语句的输出将被视为pTooltip的输入

    【讨论】:

    • 你能解释一下吗?
    • 当您说pTooltip="value" 时,这意味着使用"" 中提供的值作为pTooltip 的参数。在这里,您没有绑定来自组件的值,您只是给出了常量。要进行数据绑定,您需要[]。现在在[] 之后,这意味着将"" 中写入的任何内容与pTooltip 绑定,因此它将执行"" 中的代码,然后该语句的输出将被视为pTooltip 的输入。
    【解决方案2】:

    应该是

    [pTooltip]="(allowUpvote) ? msg1 : msg2"

    编辑:这意味着你应该放弃 *ngIf,在这种情况下你不需要它。

    【讨论】:

    • 哦。但是如果我们想要 *ngIf 呢?我不知道。我只是问问。
    • ngIf 是结构性指令,用于有条件地渲染dom中的元素,与你的用例不同
    • @Tanzeel 再试一次,这次只用[] 围绕 pTooltip`
    • 试过了。但现在我明白了。 Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 0
    • 这个[pTooltip] = "allowUpvote ? msg1 : msg2" 正在工作。 AlleXys 回答了。
    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多