Dansmith12
Dansmith12

Reputation: 143

How do i store multiple inputs in an array with ionic2/angular2

I have a dynamic list of user inputs. The user is able to add a destination by clicking "Add Destination" which generates an input field. Once the field is generated, the user enters the destination and clicks a button that should store all of the destinations in an Array. The user should be able to add multiple destinations.

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form>
    <ion-list>
  <ion-item>
    <ion-label fixed>Starting</ion-label>
    <ion-input type="text" ></ion-input>
  </ion-item>

  <ion-item *ngFor="let destination of destinations" >
    <ion-label fixed>Destination</ion-label>
    <ion-input type="text" ></ion-input>
  </ion-item>
  </ion-list>


  <button  ion-button color="light" icon-right (click)="addDestination()" >
      Add Destination
      <ion-icon name="add" ></ion-icon>
  </button>
  <div style="padding-bottom: 10px; position: absolute; bottom: 0px; width: 92%">
    <button ion-button block (click)="store()">Find Path</button>
  </div>
  </form>
</ion-content>

Typescript:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public destinations = [];

  constructor(public navCtrl: NavController) {

  }





  addDestination(){
    this.destinations.push(1);
    console.log(this.destinations);
    console.log('hello');
  }

  store(){
    console.log('hello');
    console.log(this.destinations);
  }

}

Upvotes: 0

Views: 4335

Answers (1)

yBrodsky
yBrodsky

Reputation: 5041

What I meant in my comment:

<div *ngFor="let destination of destinations; let i = index">
  <input type="text" [(ngModel)]="destinations[i]"/>
</div>

https://plnkr.co/edit/mZi1UYI9drNFRwVQsJs5?p=preview

Upvotes: 1

Related Questions