0

I'm facing the problem to replicate input fields onclick of a button *I have few input fields and i can fill the data in that *After filling the input fields i have a different data set to add so i need same fields. *If i press button (addMore) the fields should replicate and it should allow me to add one more set of data. *There should be one button(remove) that will help me to remonessessaryve those replicated fields if its not necessary.

I have tried this in angular ..and I'm sharing my sample code and plunker plz help me out

template.ts

<div class="card">
  <input type="text" id="name" value="" class="form-control">
  <label for="form1">Name</label>
  <input type="text" id="mobile" value="" class="form-control">
  <label for="form1">Mobile</label>
</div>

<button type="button" title="Add"class="btn btn-sm" 
(click)="addMore">Add</button>

test.component.ts

export class App {

  addMore() {
    //function to replicate the form input fields
  }

plunker link :- http://plnkr.co/edit/GCCnoMkLynpELwaYX11m?p=preview

2 Answers 2

2

You're looking for generating dynamic inputs using ngFor

You can initially create an array with initial value as follows,

 inputelements = [{name: '',mobile:''}];

on click of addmore button you can push more elements and those will be rendered using ngFor

Template code will be,

  <div class="card" *ngFor="let word of inputelements; let in=index" class="col-sm-3">
      <div class="form-group">
       <label for="form1">Name</label>
        <input type="text" [(ngModel)]="inputelements[in].name"  class="form-control"  required>
          <label for="form1">Mobile</label>
            <input type="text" [(ngModel)]="inputelements[in].mobile"  class="form-control"  required>

      </div>
  </div>
 <br>
<button type="button" title="Add"class="btn btn-sm pull-right" 
(click)="addMore()">Add</button>

WORKING DEMO

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

2 Comments

perfect ..@Sajeetharan .thanks bro ..If i need to remove the added fields i can do it by array indexing right??
@DeepakVijay yes you can remove by passing index and use splice
1

Keep the track of the inputs with an array and add/remove with js :

  inputs = [];

  add() {
    this.inputs.splice(0,0,this.inputs.length+1);
  }

DEMO

Comments

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.