Tan*_*jel 1 jquery datatables angular
我在这里遇到一个非常尴尬的问题...来自jQuery函数的Angular 5变量值正在改变,但没有反映/绑定视图中的新值:
在组件中:
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);
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
该函数正在调用,并且helloString变量值在函数中发生变化,更新后的值也在控制台中显示,但未反映在视图中.任何帮助都将受到高度赞赏.
发生这种情况是因为你的jquery方法没有触发angular的变化检测,因为它没有在ngZone中注册为异步事件,这是角度用来知道何时应该检测到变化.
最好的建议是......不要这样做并删除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);
});
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
而现在角度会知道发生了什么,它需要改变检测
| 归档时间: |
|
| 查看次数: |
905 次 |
| 最近记录: |