How to use the built-in if statement inside a parenthesis

I want to use inline if in an angular2 template, how is it?

<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}}it possible using the built-in if statement?

+4
source share
2 answers

The first conversion of the element name to boolean on !!below should work

{{!!item.name ? item.name : item}}
+5
source

You can use the ternary operator (what you are already using) or use the tag <template>( 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 ngSwitchinstead *ngIf, but it does not change much.

<template> , HTML, .

+2

Source: https://habr.com/ru/post/1667734/


All Articles