在Angular中,如果通过jQuery更新了DOM元素,Angular默认不会重新渲染。解决这个问题的方法是使用NgZone
服务手动触发变更检测。
首先,确保在组件中注入NgZone
服务:
import { Component, NgZone } from '@angular/core';
@Component({
// ...
})
export class YourComponent {
constructor(private ngZone: NgZone) {}
// ...
}
然后,在使用jQuery更新DOM元素的代码块中,使用NgZone.run()
方法来确保变更检测被触发:
import { Component, NgZone, AfterViewInit } from '@angular/core';
declare var $: any;
@Component({
// ...
})
export class YourComponent implements AfterViewInit {
constructor(private ngZone: NgZone) {}
ngAfterViewInit() {
this.ngZone.run(() => {
// 使用jQuery更新DOM元素的代码
// ...
});
}
}
通过在ngAfterViewInit()
方法中使用ngZone.run()
,我们确保了jQuery更新DOM元素的代码在Angular的变更检测范围内运行。这样,Angular会检测到DOM的变化并进行重新渲染。