双向绑定[(ngmodel)]不受jquery更改事件的影响

问题描述 投票:0回答:1

我需要在js change事件上更新角度模型,这是一个简化的隔离演示:

英雄form.component.html:

<button type="button" id='btn1'>change</button>
<input type="text" id="txt1" name="txt1" [(ngModel)]="str1" />{{str1}}

英雄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绑定的模型?

javascript jquery angular angular7
1个回答
2
投票

在角度项目中,我们不应该像你的方式那样实现你的要求。

您可以使用(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}}

但是:ぁzxswい

© www.soinside.com 2019 - 2024. All rights reserved.