OreoFanatics
OreoFanatics

Reputation: 898

Angular 4 - Generate select value from comma separated string

I have a string with comma separated values. I would like to have this as the option value for my select form (drop-down box)

Example:

itemA, itemB, itemC

Into (consider this as a select form):

[Please select a value]:
itemA
itemB
itemC

How to achieve this?

Upvotes: 1

Views: 2724

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222682

You need to use .split(',')

<select [(ngModel)]="selectedMetric">
     <option *ngFor="let metric of  toArray" [ngValue]="metric">{{metric}}</option>
</select>

AND in component.ts

export class AppComponent  {
  name = 'Angular 4';
  DATA =  'itemA, itemB, itemC';
  toArray =  this.DATA.replace(/ /g, '').split(',')
}

DEMO

Upvotes: 0

L&#233;o R.
L&#233;o R.

Reputation: 2708

You need to slit your String and create an Array, after you can add NgFor to add your value in a select :

Assuming that you have got you data in data

let optionsplit =  this.data.split(',');

In view

<select name="yourinput">
   <option ng-repeat="o in optionsplit" value="{{o}}">{{o}}</option>
<select>

Or with ng-options

<select ng-options="o for o in optionsplit">

</select>

Upvotes: 1

Related Questions