Reputation: 788
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?
Upvotes: 0
Views: 1448
Reputation: 1749
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>
Upvotes: 1