Search code examples
jqueryangularng-submitngmodel

Angular 4 ngSubmit not getting values from jquery populated inputs


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> 

Solution

  • 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);