0

I populate form input field values programmatically with jquery. The values are visible in the form. When I console.log the form data on submit, that data doesn't contain the values. When i modify the values manually, the data does contain the values:

I run a function that populates an input field:

 $('#itemNum').val('myNewValue');

That populates an input like so:

<input type="text" [(ngModel)]="item.number" name="number" id="itemNumber" class="form-control">

I can see this newly populated value in the input field fine. If I edit that input, I can get the value on submit. But if I leave it as is, it only return the component defined properties:

export class MyComponent implements OnInit {
  item: Item = {
    number:0,
    ...
  }
  onSubmit(value){ console.log(value) }
}

How can I get ngForm/ngModel/ngSubmit to see these jquery populated values?

fyi, my form looks like this:

<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<input type="text" [(ngModel)]="item.number" name="number" id="itemNumber" class="form-control">
...
<input type="submit" class="btn btn-primary" value="Confirm">
</form> 

1 Answer 1

1

Angular and jQuery are different things, there's no way for Angular to know of changes made by jQuery, which you should not be using since that's what you're using Angular for.

If you need to change the value programmatically, then simply:

this.item.number = 10;

And if you were using Reactive Forms instead then you would do it like this:

this.form.get('item.number').setValue(10);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Christian, I came to realize that after seeing stackoverflow.com/a/17110709/4493441 . My challenge was trying to build a form from a table row built via ngFor loop. I realized the form was just duplicating effort and just ran my submit function straight from that table row where all the data was anyway. Thanks for your help!

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.