NewUser
NewUser

Reputation: 13313

Angular 4 format string into html form options

In angular 4 I have a component where I am getting the data for form fields which user has made saved. So basically I am getting data like this

data = [
    {type: "option", label: "Country", options: "India, Sri Lanka"},
    {type: "option", label: "Size", options: "Large, Small, Extra Large"},
    {type: "radio", label: "Gender", options: "Male, Female"}
]

Now I want to use those data in the html and build a form. So when type is option then it would be a select option type with those options. If it the type will be radio then it will show radio field in the form with those options(Male, Female)

I have made my component like this

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-registration-checkout',
  templateUrl: './registration-checkout.component.html',
  styleUrls: ['./registration-checkout.component.css']
})

export class RegistrationCheckoutComponent implements OnInit {

id: any;

constructor(
    private http: HttpClient,
    protected checkOutService: CheckoutService,
    ) {
   }

   ngOnInit() {
    this.id = localStorage.getItem('id');
    this.checkOutService.getExtraFields(this.id).subscribe(     response => {
    this.fields = response['fields'];
    console.log(this.fields); // shows data in array object
    },
    err => {
      console.log(err);
    });
   }
}

In HTML I have made my code like this

<div *ngFor = "let form of fields; let i = index">
    {{form | json}}
    <div *ngIf="form.type=='option'">
        Show Select Option
        {{form.options}}

        <select>
            <option></option>
        </select>
    </div>
    <div *ngIf="form.type=='radio'">
        show Radio Option
        <input type="radio" name="">
    </div>

Here I am bit confused how to make the options for select into loop. I mean the options are now in string with comma. So how can I make that so it will look like

<select name="country">
            <option value="India">India</option>
            <option value="Sri Lanka">Sri Lanka</option>
        </select>

Upvotes: 0

Views: 262

Answers (1)

user4676340
user4676340

Reputation:

Try something like this

<div *ngFor="let form of fields; let i = index">
  <div *ngIf="form.type === 'option'">
    <select>
      <option *ngFor="let option of form.options.split(',')" [value]="option">{{ option }}</option>
    </select>
  </div>
  <div *ngIf="form.type === 'radio'">
    <ng-container *ngFor="let option of form.options.split(',')">
      <input type="radio" [name]="option"> {{ option }}
  </ng-container>
  </div>

Upvotes: 1

Related Questions