0

I have a requirement to add a field dynamically in my Ionic 4 app. I have declared an array variable in my ts file.

fields: [];

When I press the button I want to generate a new field with inputs fields. This is my code on the view:

  <ion-grid>
    <ion-row *ngFor="let field of fields">
      <ion-col>
        <ion-input></ion-input>
      </ion-col>
      <ion-col>
        <ion-input></ion-input>
      </ion-col>
    </ion-row>
  </ion-grid>

This is my code for the button:

 <ion-button expand="full" (click)="addField()">Add field</ion-button>

How can I add a row dynamically when I press the button?

1 Answer 1

1

Here is a plunker that gives an example of how this is possible: https://embed.plnkr.co/6YPQXH/

Basically you have an array of values for the input values:

 words2 = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}, {value: ''}];

and you add to it in your method addField()

You can iterate through adding accessing the values with the index as such:

<div *ngFor="let word2 of words2; in as index" class="col-sm-3">
        <div class="form-group">
          <input type="text" [(ngModel)]="words2[in].value" name="name{{in}}" class="form-control" #name="ngModel" required />
        </div>
        <br />
    </div>
Sign up to request clarification or add additional context in comments.

3 Comments

This is the style of HTML do you have the Ionic 4 version for this?
NgFor is from the same module; you can use ion-input if needed in place of input
I gonna test it I will let you know!

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.