javascript - 双向绑定 [(ngmodel)] 不受 jquery 更改事件的影响
问题描述
我需要在 js 更改事件上更新角度模型,这是一个简化的、独立的演示:
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 绑定的模型?
解决方案
在 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}}
推荐阅读
- asp.net - 带有列表的 EF Core 更新
- php - mysql_query($query, $connection) 与 mysqli_query($connection, $query)
- python - “NoneType”对象不可调用 Python
- docker - 在没有 Jenkinsfile 的 Jenkins 中与 Docker 并行运行 Cypress
- spring-webflux - 有没有办法控制在 Reactor Netty 的 TcpClient 中读取的字节数?
- html - 无法设置圆圈位置
- csv - 在 Julia 中读取 .dat 文件,可变分隔符间距的问题
- python - Python中嵌套函数模式的用例是什么?
- json - CICS TS(DFHJS2LS):当从 POSTMAN 工具接收到 MAINFRAME 时,汉字正在损坏
- node.js - 使用客户端凭据的 Node.js https.request 方法