3

enter image description here

  addDetails() {
     const divCreate = document.createElement('div');
     divCreate.appendChild(document.createTextNode('Some text'));
     divCreate.setAttribute('class', 'bg-secondary');
     document.getElementById('mainForm').appendChild(divCreate);
  }

The image attached is my form, and onclick I want to add similar form, and once done will submit all values to db.

5
  • please post the code that you have tried Commented Nov 16, 2018 at 12:07
  • addDetails() { const divCreate = document.createElement('div'); divCreate.appendChild(document.createTextNode('Some text')); divCreate.setAttribute('class', 'bg-secondary'); document.getElementById('mainForm').appendChild(divCreate); } This is what I tried of creating using multiple attribute, but was not helpful Commented Nov 16, 2018 at 12:09
  • please add code to the question body Commented Nov 16, 2018 at 12:09
  • Okay done with changes Commented Nov 16, 2018 at 12:19
  • 1
    So what is your question? That function not doing what you want? (Don’t see even an attempt to create actual form elements in there.) “onclick I want to add similar form, and once done will submit all values to db” - then you don’t want to add an actual extra form (those submit individually only), but another set of form elements to the same, already existing form. Commented Nov 16, 2018 at 12:23

1 Answer 1

4

You can do it in the following way (you will need to add validation too but here is a plain working demo https://stackblitz.com/edit/angular-p3cztw):

Html code

<div *ngFor="let item of formDataList;let i = index;">
<form  >
  <input type="text" [(ngModel)]="item.detail" name="detail" />
  <input type="text" [(ngModel)]="item.amount" name="amount" />
  <input type="date" [(ngModel)]="item.date" name="date" />
  <button (click)="removeItem(item)"> remove </button>
</form>
</div>

<form #addForm="ngForm" >
  <input type="text" [(ngModel)]="data.detail" name="detail" />
  <input type="text" [(ngModel)]="data.amount" name="amount" />
  <input type="date" [(ngModel)]="data.date" name="date" />
  <br/>
  <button (click)="addItem(data)"> add  </button>
</form>

Ts code :

   public data = { };
   public formDataList = [];

   addItem($item){
       this.formDataList.push($item)
       this.data = {};
    }

   removeItem($item){
       this.formDataList.splice( this.formDataList.indexOf($item),1)

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

1 Comment

Thanks buddy...that was what I was looking for..I tried with one form actually...

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.