2
votes

I have created an Angular form following this article (http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/):

<div *ngFor="let data of somevar.records">
  <form #abc_form="ngForm" (ngSubmit)="onSubmit(abc_form.value)">
    {{data.id}}    // prints 5
    <input name="id" type="hidden" value={{data.id}} ngModel>
    <input type="radio" name="name" value={{data.id}} ngModel>

    <div class="submit-button">
      <button type="submit">Save</button>
    </div>
  </form>
</div>

The data hash in component looks something like:

somevar = {records: [{id: 5}, {id: 6}]}

Here, when I directly interpolate data.id in view it prints 5 in UI. But, when I try assigning it as a value to an hidden input field, it isn't present. Hence, upon form submission ID parameter is not present.

What is wrong here? What is the correct way to pass ID then?

EDIT

I also tried:

<input name="id" type="hidden" [value]="data.id" ngModel>

NOTE The value gets assigned to the hidden field when I remove ngModel:

<input name="id" type="hidden" [value]="data.id">

OR

<input name="id" type="hidden" value={{data.id}}>

Both the above works and creates hidden inputs with values assigned. But, it's not part of ngModel anymore

3
can you try using this [ngModel] = "data.id" ? - Rahul Singh
Yes that works, can you please explain? - Abhi
@RahulSingh Can you explain why the radio element works, but input element doesn't. plnkr.co/edit/GGU7imcBCCJFWVsGgR89?p=preview - Abhi

3 Answers

2
votes

Instead of using ngModel and value, you can use [ngModel] to bind the value:

<input type="hidden" name="id" [ngModel]="data.id">

Now it will be part of your form.

DEMO: http://plnkr.co/edit/oF5lFSbMbyltB0Mgi6hi?p=preview

2
votes

When creating multiple ngModel controls inside ngFor loop each control and name must be unique

You can try this :

<div *ngFor="let data of somevar.records;let index = index;trackBy:trackByIndex;">
  <form #abc_form="ngForm" (ngSubmit)="onSubmit(abc_form.value)">
    {{data.id}}    // prints 5
    <input name="id_{{index}}" type="hidden" [ngModel]=data[index].id>

    <div class="submit-button">
      <button type="submit">Save</button>
    </div>
  </form>
</div>
0
votes

To use the data binding you need to change your hidden input to this:

<input name="id" type="hidden" [value]=data.id>

Remove the ngModel because it the data binding via [value] and the ngModel could interfere with each other.

EDIT My bad, of course you have to remove the curly braces too.