Youngz ie
Youngz ie

Reputation: 679

How using inline if statement inside bracket

I want using inline if statement in angular2 template like this?

<select [(ngModel)]="value" class="form-control" (blur)="onBlur()">
    <option *ngFor="let item of items" [ngValue]="item">{{item.name?item.name:item}}</option>
</select>

how to make {{item.name?item.name:item}} posible using inline if statement?

Upvotes: 21

Views: 32342

Answers (2)

smnbbrv
smnbbrv

Reputation: 24551

You can use a ternary operator (that's what you already use) or use <template> tag (see more):

<select [(ngModel)]="value" class="form-control" (blur)="onBlur()">
  <option *ngFor="let item of items" [ngValue]="item">
    <template [ngIf]="item.name">{{ item.name }}</template>
    <template [ngIf]="!item.name">{{ item }}</template>
  </option>
</select>

Of course you can use ngSwitch instead of *ngIf, but it does not change a lot.

The advantage of using <template> tag is that it does not create a real HTML tag which is not allowed inside of option.

Upvotes: 3

First convert item name to boolean by !! below should work

{{!!item.name ? item.name : item}}

Upvotes: 34

Related Questions