Add fields to registration form dynamically


#1

I have registration form tied via ngModel with my actual model.
My model:

export class RegistrationFormModel {
  FirstName: string;
  LastName: string;
  Gender: string;
  DOB: string;
  Phones: Array<{Phone: string;}>;
  Email: string;
}

I want to add phones dynamically with icon click.
My registration form part:

<ion-item>
     <ion-label floating>Phone number*</ion-label>
            <ion-input type="tel" required [(ngModel)]="regModel.Phones[0].Phone" name="Phone"></ion-input>
            <ion-icon name="ios-add-circle-outline" item-right no-padding (click)="testClick()"></ion-icon>
  </ion-item>

So, basically question is in adding elements via code and retrieving information after. How can I achieve this?

P.S. Excuse me if this is silly question, but I’m new with Ionic 2 and things in native android development are quite different :stuck_out_tongue:


#2

When you have an array in the backing model, you can do things like this:

<ion-item *ngFor="let tel of regModel.Phones">
  <ion-input [(ngModel)]="tel">
</ion-item>

Then, when you just add a new element to the Phones array of ngModel, a new input item should magically appear.


#3

Nice, thank you. It seems I cannot get used to this two-way data binding magic. And some caveat for the ‘next’ guys - ngModel doesn’t work with local variables.

  <ion-item *ngFor="let phones of regModel.Phones; let i = index">
    <ion-label floating>Phone number*</ion-label>
    <ion-input type="tel" required [(ngModel)]="regModel.Phones[i].Phone" name="phones"></ion-input>
    <ion-icon name="ios-add-circle-outline" item-right no-padding (click)="addPhone()"></ion-icon>
  </ion-item>

//in ***.ts file

  addPhone() {
    this.regModel.Phones.push({Phone: ''});
  }