Shivani
Shivani

Reputation: 301

How to keep adding text box on every click using ngIf

On the event of a button click, I am adding a new field box on the screen. But this happens only for one click. I want to know how can I achieve to keep adding field boxes every time the button clicks?

Here is my code: https://stackblitz.com/edit/angular-pgsfrm

Upvotes: 0

Views: 394

Answers (2)

Elfayer
Elfayer

Reputation: 4561

Here I have simplified a bit your example: Demo

Basically you are gonna need an array of strings to store all via values:

viaFields: Array<string> = ['']

Then simply display these using an *ngFor loop and [(ngModel)] for data binding:

<button (click)="addField()"> + Add Via</button>
<input
  *ngFor="let field of viaFields; let in = index; trackBy: trackByFn"
  [(ngModel)]="viaFields[in]">

Upvotes: 2

Titulum
Titulum

Reputation: 11476

You should add new fields by using ngFor instead of ngIf. The amount of fields can be based on the contents of an Array for instance. You can check out how to do this in my example:

<input *ngFor="let fieldValue of fields" placeholder="{{fieldValue}}" />

Upvotes: 2

Related Questions