Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
Youngz ie Avatar asked Jan 25 '17 07:01

Youngz ie


2 Answers

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

{{!!item.name ? item.name : item}}
like image 193
Salih Şenol Çakarcı Avatar answered Nov 19 '22 10:11

Salih Şenol Çakarcı


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.

like image 3
smnbbrv Avatar answered Nov 19 '22 12:11

smnbbrv