jquery - 从 jQuery 函数更新 Angular 5 变量值和 View 中的绑定(bind)

标签 jquery angular datatables

我在这里面临一个非常尴尬的问题...来自 jQuery 函数的 Angular 5 变量值正在更改,但没有反射(reflect)/绑定(bind) View 中的新值:

在组件中:

import { Component, OnInit } from '@angular/core';
    declare var $: any;

    export class TestComponent implements OnInit {

    helloString: string = 'Hello World';

    ngOnInit() {
        $(() => {
          $(document).on('click', '#testButton', () => {
            this.helloString= "Not Hello World";
            console.log(this.helloString);
          });
        });
      }
    }

在 HTML 中:

    <div>{{helloString}}</div>

    //This button is in jQuery Datatable row..that's why I need the call function from jQuery

    <button type="button" id="testButton" class="btn btn-info btn-sm">Test Button</button>

函数正在正确调用,并且 helloString 变量值在函数中发生变化,更新后的值也显示在控制台中,但没有反射(reflect)在 View 中。任何帮助将不胜感激。

最佳答案

发生这种情况是因为你的 jquery 方法没有触发 Angular 的更改检测,因为它没有在 ngZone 中注册为异步事件,而 ngZone 正是 AngZone 用来知道何时应该检测更改的。

最好的建议是...不要这样做并删除 jquery 依赖项...但如果必须,那么您可以直接使用 ngZone 在 ngZone 内运行:

import { Component, OnInit, NgZone } from '@angular/core';
declare var $: any;

export class TestComponent implements OnInit {

  helloString: string = 'Hello World';

  constructor(private _ngZone: NgZone) {}

  ngOnInit() {
    $(() => {
      $(document).on('click', '#testButton', () => {
        this._ngZone.run(() => {
          this.helloString= "Not Hello World";
          console.log(this.helloString);
        });
      });
    });
  }
}

现在 Angular 会知道发生了一些事情并且需要更改检测

关于jquery - 从 jQuery 函数更新 Angular 5 变量值和 View 中的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598424/

相关文章:

javascript - 尝试从 "observable' s 链获取可观察性时出现错误”

javascript - 获取 jquery 单元格数据

javascript - Bootstrap数据表排序

javascript - 重叠jquery鼠标悬停事件

javascript - 编辑字段时如何将 id 号发送到 Jquery 模式表单中?

javascript - 将页脚贴在底部(显示时)

css - Angular 组件在 View 初始化后获取组件宽度高度

javascript - 将java日期转换为 Angular 日期

php - 数据表: update table in realtime with animation

javascript - jQuery:如何为输入字段值设置固定小数