首页 > 解决方案 > 双向绑定 [(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 绑定的模型?

标签: javascriptjqueryangularangular7

解决方案


在 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}}

演示:https ://stackblitz.com/edit/angular-click-change-value


推荐阅读