7

So I have a code here in this stackblitz example.

Basicly there is a simple form, with an input and a button. Pressing the button will copy the input's current value to a label:

enter image description here

after click:

enter image description here

html:

<input id="inputID" [(ngModel)]="inputValue" />
<button id="buttonID" (click)="set()">send</button>
<hr/>
<label> new Value: {{labelValue}} </label>
<hr/>

JS:

  labelValue = "";
  inputValue = "defaultValue";

  set(){
    this.labelValue = JSON.parse(JSON.stringify(this.inputValue));
  }

I have to simulate the user interaction using only native JS code. So I try the following (in browser console for instance):

 - document.getElementById('inputID').value = "aNewValue"; 
 - document.getElementById('buttonID').click();

The problem is this:

enter image description here

I got the default value in the label, not the current value. How can I get the right value? I suspect that it is something around reflected properties, but cannot figure out what can be the problem here.

Update: I have tried the following, with no luck either.

element = document.getElementById('inputID')
element.value = "aNewValue"; 
var ev = new Event('change', {
    view: window, 
    bubbles: true,
    cancelable: true,
  });
element.dispatchEvent(ev);
document.getElementById('buttonID').click();
8
  • this will not happen becaue the model is not updating. angular is not aware what you are doing using dom property Commented Jul 2, 2018 at 13:53
  • Yeah, I suspect as much, but how can I simulate the interaction so the app will notice the change in the input field? Commented Jul 2, 2018 at 13:54
  • look into this stackoverflow.com/questions/17109850/… Commented Jul 2, 2018 at 13:59
  • sadly, I cannot use jQuery and I cannot triger the input change event... I am not even sure it is the same in Angular2+. Commented Jul 2, 2018 at 14:04
  • 1
    stackblitz.com/edit/native-clicker-tqxxls?file=src/app/… Commented Jul 2, 2018 at 14:08

1 Answer 1

14

Angular updates the model on input event. You should trigger it manually, after you set the value.

inputElement = document.getElementById('inputID');
buttonElement = document.getElementById('buttonID');

inputElement.value = "aNewValue";
inputElement.dispatchEvent(new Event('input', {
  view: window,
  bubbles: true,
  cancelable: true
}))
buttonElement.click();
Sign up to request clarification or add additional context in comments.

1 Comment

this works perfectly, thanks. To anyone with the same problem: It is important to understand, that in different frameworks, the event type that propagates the changes under the hood may differ. ('change' event for instance)

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.