最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular2 [innerHTML] if else validation - Stack Overflow

programmeradmin7浏览0评论

I want to display different text in a button, depending on some JSON data.

Example (of course not working):

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

I know this functionality already exisits in e.g [ngClass]:

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

Using the [ngClass] approach is displayed as [object:Object] and therefore not working.

Any solution?

I want to display different text in a button, depending on some JSON data.

Example (of course not working):

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

I know this functionality already exisits in e.g [ngClass]:

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

Using the [ngClass] approach is displayed as [object:Object] and therefore not working.

Any solution?

Share Improve this question asked Oct 18, 2016 at 16:55 VingtoftVingtoft 14.6k26 gold badges91 silver badges145 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 17

use ternary expression

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

anyway you don't need innerHtml for this. 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.

发布评论

评论列表(0)

  1. 暂无评论