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

标签 javascript jquery angular angular7

我需要在 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}}

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

关于javascript - 双向绑定(bind) [(ngmodel)] 不受 jquery 更改事件的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55902762/

相关文章:

Angular2 - Validators.compose

javascript - 在 Angular Swiper 中获取图像和标题

javascript - 组件上的 @input 给出错误 : Property 'showingSingle' does not exist on type

javascript - 我如何获得表单选择的值 jQuery

javascript - 如何使用 Jquery 删除文本区域的第一行?

javascript - uploadcare使用js存储到s3

javascript - 如何使用 jquery 从左到右或从右到左为 2 个 css 布局设置动画?

javascript - 动态更改 Bootstrap 弹出窗口的模板

javascript - 重置方法不适用于 meteor 对象

javascript - 当光标位于文本字段内时如何编写按键事件