5

I have a section with 3 fields, when click on new button, i must get the same section. I get no errors, so i am not getting where i am going wrong

Example here

HTML:

     <form *ngFor="let emergency of Emergencies; let i = index">
        <div>
          <label > Name</label>
  <input type="text"   [(ngModel)]="emergency.Name" name="emergency.Name" 
          />
        </div>
        <div>
          <label >Phone</label>
          <input type="text" OnlyNumber="true" [(ngModel)]="emergency.Phone" name="emergency.Phone"
            maxlength="15" />
        </div>
        <div>
          <label >Relations</label>
          <select class="col-lg-6 col-md-6 col-sm-6 col-xs-6"[(ngModel)]="emergency.ship">
            <option >{{ship.Description}}</option>
          </select>
        </div>
      </div>
    </form>
Bhrungarajni
  • 2,415
  • 11
  • 44
  • 88
  • There are Alot of errors in your code, check console as well – Pardeep Jain May 28 '18 at 10:57
  • is it fine if you do it with template forms using `NgModel`, since u r using `ngModel` also. – Sravan May 28 '18 at 11:00
  • @Sravan i guess that can be done, but is it possible to keep formgroup as wel and do – Bhrungarajni May 28 '18 at 11:03
  • you can use either `template driven` or `reactive` at once, if you need to do with form group check [this link](https://stackoverflow.com/questions/43520010/angular-4-form-formarray-add-a-button-to-add-or-delete-a-form-input-row) as suggested in one answer, I ll add an anwer and logic how to do using `ngModel` – Sravan May 28 '18 at 11:05
  • ya please you add me an answer, let me check with that link as wel – Bhrungarajni May 28 '18 at 11:06

2 Answers2

7

If you can use template driven forms here is an answer for you.

Add a button for creating a new field

<button (click)="addEmergency()">New</button>

Now, add addEmergency method in component:

addEmergency() {
    var item = {
      "ContactName":"Person3",
      "Phone": "122355",
      "relationship": ""
      }
    this.Emergencies.push(item);
  }

In html:

<div  *ngFor="let Emergency of Emergencies">
  Your inputs go here
</div>

Here is a demo I created out from your code

Vega
  • 27,856
  • 27
  • 95
  • 103
Sravan
  • 18,467
  • 3
  • 30
  • 54
0

You need to use FormArray to create dynamic fileds.

Go through this stack question or blog