所以我这里有一个代码 this stackblitz example .
基本上有一个简单的表单,带有一个输入和一个按钮。按下按钮会将输入的当前值复制到标签:
点击后:
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));
}
我必须仅使用 native JS 代码来模拟用户交互。 所以我尝试以下操作(例如在浏览器控制台中):
- document.getElementById('inputID').value = "aNewValue";
- document.getElementById('buttonID').click();
问题是这样的:
我得到的是标签中的默认值,不是当前值。我怎样才能得到正确的值(value)?我怀疑它是关于 reflected properties 的东西,但无法弄清楚这里可能是什么问题。
更新:我尝试了以下方法,但也没有成功。
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();
最佳答案
Angular 在 input
事件上更新模型。您应该在设置值后手动触发它。
inputElement = document.getElementById('inputID');
buttonElement = document.getElementById('buttonID');
inputElement.value = "aNewValue";
inputElement.dispatchEvent(new Event('input', {
view: window,
bubbles: true,
cancelable: true
}))
buttonElement.click();
关于javascript - 如何模拟用户对输入和按钮元素的交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51137746/