Ionic2 dynamic adding of new inputs to the form

I’m wondering how to do the same dynamic addition of inputs in ionic2 framework as it is done in Angular4 by this demo example given on stackoverflow answer

my page1.ts:

      addInputs() {
        this.anArray.push({ 'value': '' },{});
      }

page1.html:

    <ion-item *ngFor="let att of anArray; let idx = index">
       <ion-label color="light"> {{att.label}} {{idx+1}} </ion-label>
       <ion-input type="text" [(ngModel)]="anArray[idx].value"></ion-input>
    </ion-item>

    <button ion-button (click)="addInputs();">add fields</button>

but how to create two inputs with different label names as “Name:” and “Surname:” same for each new pair.

For example if I add name directly:

<ion-label color="light"> Name: {{att.label}} </ion-label>

of course this way creates two inputs with same name, and seems not really correct for my case:

this.anArray.push({ 'value': '' },{});

I’m new with Ionic2 and TypeScript, maybe I can use counter {{idx+1}} to attache Name: and Surname: labels to input field, created by one click with using even and odd value of number, but I’m not sure, how to do it properly.

Advice would be helpful

I guess I don’t fully follow the issue, you have to have a label name and a value, just like you show in your page1.html. Yet on your addInputs method you don’t have a label property defined. As long as you set a label name everything should work.

const inputs = [
  { 
    label: 'First Name',
    value: '',
  },
  {
    label: 'Middle Name',
    value: '' ,
  }
];

addLastName() {
  this.inputs.push({
    name: 'Last Name',
    value: '',
  });
}

Then basically the same html, I just cleaned stuff up a bit, like idk why you would access value by index in the array when you have the individual item from the loop.

<ion-item *ngFor="let input of inputs">
   <ion-label color="light">{{input.label}}</ion-label>
   <ion-input type="text" [(ngModel)]="input.value"></ion-input>
</ion-item>

<button ion-button (click)="addLastName();">add fields</button>
2 Likes

hi, Rob

thanks for feedback

sure

excellent