2

I just noticed that the value in component that is bind to a Inputfield is not updating when the input field's value is updated through jquery.

Component.ts

export class AppComponent{
searchString = "";
}

HTML

<input id="txSearchstring" type="text" [(ngModel)]="searchString"  >

jquery

$('#txSearchstring').val('this is a test data');

when I tried to log the value of searchString, the value is still empty.

Any suggestions?

1 Answers1

1

Angular monkey patches the browser events, setTimeout, setInterval and ajax calls using zones to run change detection mechanism. Every time the change detection code runs, it checks for changes in all the values that are bound to the template. Now in your case when the value of the input field is changed through jQuery, the browser change event is not called hence change detection doesn’t run and the changed input field value is thus not reflecting in the bound property ‘searchString’. Manually running the change detection like this after $('#txSearchstring').val('this is a test data'); will resolve the issue:

  • ChangeDetectorRef.detectChanges() (check only current component and its children). Here ChangeDetectorRef is a dependency that can be injected
  • thanks, unfortunately, this didnt work. I already added .detectChanges() and call it every seconds but still, the value inside ts is not updated. – Jesse Castro Jul 19 '18 at 10:27