1

I have this

<ul>
<li *ngFor="let data of list">
    //here bind a textbox to the id and get its value so something like

   <input type="text" /> //am stuck
</li>

export class App {
 textboxvalues:any[] = [];

list= [{
   id: 1,
   value: 'One'
  },
  {
    id: 2,
    value: 'Two'
  }];
}

How can i bind both the value and id of textboxes such that when i collect the value of

console.log(textboxvalue)

it provides {id, value} eg

{1:"textbox1", 2:"textbox2"}

Or even as an object

{1, "textbox1"}, {2, "textbox2"}
1

2 Answers 2

2

Have you tried the following:

    <li *ngFor="let data of list;">
      <input type="text" [(ngModel)]="data.value"/> 
    </li>

The [(ngModel)] sets up two way binding so that as you change the value in the textbox the object in the array is updated as well. Don't forget to import the FormsModule though.

Here is a example on plunker. Everything you'll need is in app.ts. You'll see that as you change the textboxes in the first list the read-only list is updated as well.

Hope this helps.

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

Comments

0

Would something like this work?

<li *ngFor="let data of list">
    <input type="text" name={{data.id}} [(ngModel)]="data.value"  />
</li>

This results in a form.value of:

{ "1": "One", "2": "Two" }

If you need to read from one property and write to another, you could instead try this (but I did not syntax check it). Note that it won't get the default values. It will only be set to changed values.

<li *ngFor="let data of list; let i = index">
    <input type="text" name={{data.id}} [ngModel]="data.value"
           (ngModelChange)="textboxvalues[i]=$event  />
</li>

2 Comments

How do i pass the values directly to textboxvalues, i can see your bind is to data.value
Put code in the submit button to take yourForm.value and write the values into the array.

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.