1

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?

0

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

Given the string, this would rather be let metric of this.data.replace(/ /g, '').split(','). Otherwise, your values will have spaces.
Or maybe [ngValue]="metric.trim()"
I received an error: Uncaught Error: Template parse errors: Parser Error: Unexpected token / at column 59 in [let books of currentModel.books.authors.replace(/ /g, '').split(',')] What does / /g means?
@Sajeetharan what if the data is retrieved from restAPI? Would that make any difference on the way of splitting it?
even if you recieved from api, it will be the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.