我需要在 js 更改事件上更新 Angular 模型, 这是一个简化的、独立的演示:
hero-form.component.html:
<button type="button" id='btn1'>change</button>
<input type="text" id="txt1" name="txt1" [(ngModel)]="str1" />{{str1}}
hero-form.component.ts:
...
import * as $ from "jquery";
...
export class HeroFormComponent implements OnInit {
str1 = "initval";
ngAfterViewInit(){
var txt1 = $('#txt1');
$('#btn1').on('click', function(){
txt1.val('new val').change();
// when js/jquery triggers a change on the input, I need the str1
// which was bound using [(ngModel)] to be updated
});
}
单击按钮时,文本框的值更改为 new val
但插值 {{str1}}
不受影响,但是如果我更改手动文本框可以工作。
是否可以在 js 更改事件上更新与 ngmodel 绑定(bind)的模型?
最佳答案
在 Angular 项目中,我们不应该按照您的方式实现您的要求。
您可以使用(click)
事件和#txt1
来获取值
在 ts 组件中实现更改 str1 值。
export class AppComponent {
name = 'Binding data in Angular';
str1 = "initval";
ngAfterViewInit() {
}
change(val) {
console.log(val)
this.str1 = val;
}
}
更新了 HTML
<hello name="{{ name }}"></hello>
<button type="button" id='btn1' (click)="change(txt1.value)">change</button>
<input type="text" #txt1 id="txt1" name="txt1" />{{str1}}
关于javascript - 双向绑定(bind) [(ngmodel)] 不受 jquery 更改事件的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902762/