- Published on
String to Json Array with a Pipe for Select Options in Angular
- Authors
- Name
- Oğuzhan Kırçalı
In a business rule table, we stored units of measurement in a cell as a json array string. This data can be changed for all rows, therefore it should be dynamic and used as options of a select element.
["km","m","cm","mm"]
I need to get this json string from database and bind to a select element as options. Users can change these units in an administrative page. Pipes are very useful for these kind of jobs. So I created a pipe like below.
Add a Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'stringToArray'})
export class StringToArrayPipe implements PipeTransform {
transform(value): Object {
Add Pipe to Module
You should add the pipe class to your NgModule
@NgModule({
providers: [
FileDownloadService,
StringToArrayPipe
],
declarations: [
AutoFocusDirective,
StringToArrayPipe
],
exports: [
ButtonBusyDirective,
StringToArrayPipe
]
})
Use the Pipe
The next step should be putting select element into the page. String element is coming on my model. Now, It's time to use the pipe.
<select class="form-control">
<option *ngFor="let unit of (myModel.measurementUnits | stringToArray)" [ngValue]="unit">
{ {unit} }
</option>
</select>