Angular 2 ngClass: 在尝试在HTML上显示JSON时,使用插值符号({{}})而期望表达式的地方出现了错误

4

我是Angular 2的新手,希望能得到社区的帮助。我目前正在尝试在html视图中的<tr>元素中实现ngClass的动态/条件实现。使用的truify是一个变量,其原始值来自设置在我的组件上的JSON对象:

<td [ngClass] = "{weak : {{jsonInMyComponenet.element}}, neutral : !{{jsonInMyComponenet.element}}}"  ></td>

当我使用上述代码时,出现以下错误:
在预期表达式的地方得到了插值({{}})。
如果我删除大括号,就不会出现错误,但页面不会呈现弱或中性类实现,所以我看不到它们。 我做错了什么?
1个回答

6
不要同时使用[...]{{...}}。只能选择其中一种。
<td [ngClass] = "{'weak' : jsonInMyComponenet.element, 'neutral' : !jsonInMyComponenet.element}"  ></td>

{{...}}用于字符串插值。 [...]将该值解释为表达式。


1
谢谢Gunter,是的我已经删除了它,但是这个类没有渲染。它应该有一个红色或灰色的背景颜色,但目前是白色的。我不确定,也许我的JSON数据不正确: { "jsonInMyComponenet": true, "jsonInMyComponenet1": false, "jsonInMyComponenet2" : true} - joeCarpenter
我忘了当属性名是字面名称时需要用引号括起来。 - Günter Zöchbauer
好的,在这种情况下,对于那些应该评估为false的变量怎么处理?我尝试了“!jsonInMyComponenet.element”和“!'!jsonInMyComponenet.element'”,但是没有渲染出来:( - joeCarpenter
1
只需要使用 !jsonInMyComponenet.element 即可,就像我在回答中展示的 neutral 一样。 - Günter Zöchbauer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接