在Angular 8中,表达式在检查后发生了变化的解决方法是使用ChangeDetectorRef的detectChanges()方法来强制更新视图。
首先,在组件的构造函数中注入ChangeDetectorRef:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-your-component',
template: `
{{ yourExpression }}
`
})
export class YourComponent implements OnInit {
yourExpression: string;
constructor(private cdRef: ChangeDetectorRef) { }
ngOnInit() {
this.yourExpression = 'Initial Value';
}
updateExpression() {
this.yourExpression = 'Updated Value';
this.cdRef.detectChanges();
}
}
在上面的示例中,组件有一个yourExpression属性,它在初始化时设置为'Initial Value'。当点击按钮时,updateExpression()方法会将yourExpression属性的值更新为'Updated Value'。然后,我们调用cdRef.detectChanges()来通知Angular检查变化并更新视图。
这样,当你点击按钮时,视图将显示'Updated Value'。
请注意,使用detectChanges()方法来强制更新视图可能会导致性能问题,因此请谨慎使用。只有在特定情况下,例如在异步操作完成后更新视图时,才应该使用它。