0

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);
  }

}
2
  • ngModel will be = destinations[$index]. So each input has holds a value of the array Commented Mar 16, 2017 at 17:37
  • is that with angular2? Commented Mar 16, 2017 at 17:52

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

7 Comments

This has partly worked mate thanks! But the problem now is that whenever I add a destination, all of the input fields are cleared of any input. Is there a way to save the inputs to the fields?
I don't understand what you mean. Works for me: plnkr.co/edit/ZzU3StsH7p4QNKvtPGTQ?p=preview
With your solution if you add input in one of the boxes it fills other boxes.
Check this: plnkr.co/edit/GVP5GZfXTQinoV683ssA?p=preview || I replaced your array of strings with an array of objects. Works better in my opinion.
can you add a viewletters() function that console.logs all the objects in the destinations array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.