当Angular绑定不更新时,可以尝试以下解决方法:
ChangeDetectorRef
来强制更新绑定值。在组件中注入ChangeDetectorRef
,然后在需要更新绑定值的地方调用detectChanges()
方法。import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ data }}
`
})
export class ExampleComponent {
data: string;
constructor(private cdr: ChangeDetectorRef) { }
updateData() {
this.data = 'New Data';
this.cdr.detectChanges();
}
}
ngZone
:在组件中注入NgZone
,然后在需要更新绑定值的地方运行NgZone.run()
方法。import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-example',
template: `
{{ data }}
`
})
export class ExampleComponent {
data: string;
constructor(private ngZone: NgZone) { }
updateData() {
this.ngZone.run(() => {
this.data = 'New Data';
});
}
}
async
管道:将需要更新的绑定值包装在Observable
中,并使用async
管道在模板中订阅该Observable
。import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ data$ | async }}
`
})
export class ExampleComponent {
data$: Observable;
constructor() {
this.data$ = of('Initial Data');
}
updateData() {
this.data$ = of('New Data');
}
}
通过使用上述解决方法之一,可以确保Angular绑定在数据更改时正确更新。