简体   繁体   English

Angular2 [innerHTML] if else验证

[英]Angular2 [innerHTML] if else validation

I want to display different text in a button, depending on some JSON data. 我想在按钮中显示不同的文本,具体取决于一些JSON数据。

Example (of course not working): 示例(当然不起作用):

<button [innerHTML]='"Male" if user.gender==1 else "Female"'></button>

I know this functionality already exisits in eg [ngClass]: 我知道这个功能已经存在于例如[ngClass]中:

<button [ngClass]='{"btn-success": data.complete, "btn-primary": !data.complete}'>Some text</button>

Using the [ngClass] approach is displayed as [object:Object] and therefore not working. 使用[ngClass]方法显示为[object:Object],因此无法正常工作。

Any solution? 有解决方案吗

use ternary expression 使用三元表达式

<button [innerHTML]='user.gender == 1 ? "Male" : "Female"'></button>

anyway you don't need innerHtml for this. 无论如何你不需要innerHtml I'd do it like: 我会这样做:

<button>{{ user.gender == 1 ? "Male" : "Female" }}</button>

A more flexible way is just bind to a variable as the button text. 更灵活的方式是将变量绑定为按钮文本。

Like this 像这样

<button>{{buttonText}}</button>

and in your .ts file, just setting the value of buttonText based on your json value. 在你的.ts文件中,只需根据你的json值设置buttonText的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM