Manspof
Manspof

Reputation: 357

Ionic 2 Adding form fields dynamically

I'm looking to add input field dynamically, is it possible? someone has example how to do that? For example when i choose from my select options 2 input field it shows me and one i choose 5 input fields it shows me 5 input fields

I thought to do something like that

 <ion-item>
    <ion-label fixed>Field 1</ion-label>
    <ion-input type="text" value=""></ion-input>
  </ion-item>

  <ion-item *ngIf="someVariable === 'value1'">
    <ion-label fixed>Field 2</ion-label>
    <ion-input type="text" value=""></ion-input>
  </ion-item>

</ion-list>
Then i bind select to someVariable:

<ion-item>
  <ion-label>Options</ion-label>
  <ion-select [(ngModel)]="someVariable">
    <ion-option value="value1" selected="true">Option 1</ion-option>
    <ion-option value="value2">Option 2</ion-option>
  </ion-select>
</ion-item>

that's good but let's suppose i have 8 options and if user choose option 5 so it shows his 5 input fields, how can i do that? in addition if i do that, i need to declare variables dynamically because option 5 value i need to assign to specific variable.

Upvotes: 2

Views: 4689

Answers (2)

johnny
johnny

Reputation: 5097

Do you mean to show/hide multiple form fields together? You can group them and use ngIf to toggle them.

<div *ngIf="someVariable === 'option2'"> <!-- your condition here, put all the related fields as the children of this div -->
  <ion-item *ngFor="let field of option2Fields">
    <ion-label fixed>{{field.label}}</ion-label>
    <ion-input type="text" value=""></ion-input>
  </ion-item>    
</div>

Upvotes: 0

Vova Bilyachat
Vova Bilyachat

Reputation: 19474

One of the options would be reactive forms

Template

<form [formGroup]="registerForm" class="form-horizontal">
  <ion-item *ngFor="let item of fields" [ngClass]="{'has-error': registerForm.controls[item.id].errors}">
      <ion-label fixed>{{item.key}}</ion-label>
      <ion-input type="text" formControlName="{{item.key}}"></ion-input>
  </ion-item>
</form>

<ion-item>
  <ion-label>Options</ion-label>
  <ion-select (change)="onFieldChange($event.target.value)">
    <ion-option value="1" selected="true">Option 1</ion-option>
    <ion-option value="2">Option 2</ion-option>
  </ion-select>
</ion-item>

component

import { Http, Headers } from "@angular/http";
import { ActivatedRoute } from "@angular/router";
import { Component } from "@angular/core";
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent {
    fields = [];
    registerForm: FormGroup = new FormGroup({});
    constructor(private formBuilder: FormBuilder) {

    }

    onFieldChange(totalFields) {
        var properties = [];
        for (var i = 0; i < totalFields; i++) {
            properties.push({ key: "field_" + i })
        }
    }

   get value() {
    //this will return form values as object
    return this.registerForm.getRawValue();
  }

    setupForm(_properties) {
         var formData = {};
        _properties.forEach(element => {
            var key = element.key;
            formData[key] = ['default value if needed'];
            //here you can write logic if you want fields to be required
            if (true) {
                formData[key].push(Validators.required);
            }
        });

        this.registerForm = this.formBuilder.group(formData);
        this.registerForm.valueChanges.subscribe(() => {
            //if you wish here you can emit events when values changed in the form
        });

        this.fields = _properties;
    }

    title = "app works!";
}

Upvotes: 2

Related Questions