可以通过调用 changeDetectorRef.detectChanges()
方法来强制更新视图。例如:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `{{ message }}
`
})
export class ExampleComponent {
message: string;
constructor(private cd: ChangeDetectorRef) {}
updateMessage(): void {
this.message = 'Hello, World!';
this.cd.detectChanges();
}
}
在上面的示例中,点击“Update message”按钮将更新 message
值,并且使用 changeDetectorRef.detectChanges()
方法来强制更新视图。这将确保消息文本被正确地显示在页面上。
下一篇:Angular文本框默认值未显示