Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度8值赢得';更改后不更新视图_Javascript_Angular_Angular8_Angular2 Changedetection_Angular Changedetection - Fatal编程技术网

Javascript 角度8值赢得';更改后不更新视图

Javascript 角度8值赢得';更改后不更新视图,javascript,angular,angular8,angular2-changedetection,angular-changedetection,Javascript,Angular,Angular8,Angular2 Changedetection,Angular Changedetection,我在Angular中有一个小组件,其中有一个方法(目前)设置超时并更改变量的值 从'@angular/core'导入{Component,ChangeDetectionStrategy}; @组成部分({ 选择器:“我的组件”, templateUrl:“./my view.html”, 样式URL:['./我的视图.scss'], changeDetection:ChangeDetectionStrategy.Default }) 导出类MyComponent{ 状态:boolean=fals

我在Angular中有一个小组件,其中有一个方法(目前)设置超时并更改变量的值

从'@angular/core'导入{Component,ChangeDetectionStrategy};
@组成部分({
选择器:“我的组件”,
templateUrl:“./my view.html”,
样式URL:['./我的视图.scss'],
changeDetection:ChangeDetectionStrategy.Default
})
导出类MyComponent{
状态:boolean=false;
changeStatus():无效{
设置超时(()=>{
this.status=true;
}, 1500);
}
}
和HTML


;
改变状态
取消
拯救
如果我在组件中记录“status”的值。我得到了新的值'true',但它不会在视图上更改,除非我将光标聚焦在输入上,然后单击输入之外的任何位置


为什么会这样?我该如何解决它呢?

您在正常的变更检测周期之外执行此操作。这将有助于:

export class MyComponent {

  status: boolean = false;

  constructor(private _cdr: ChangeDetectorRef) { }

  changeStatus(): void {

  setTimeout(() => {
    this.status = true;
    this._cdr.detectChanges()
  }, 1500);
 }
}

编辑:它会在下次与UI交互时更新,因为angular会在该时间点运行其更改检测,它会捕获组件中的更改并更新UI。如果您以异步方式进行操作(除非您使用的是angular API,如HttpService),那么您必须告诉ChangeDetector有手动更改。

为什么会发生这种情况?

您可以在一个祖先组件中将
changeDetection
设置为
OnPush
。无法覆盖该属性。参考:

我如何解决它?

取消设置祖先组件中的changeDetection,或手动检测更改,如Adam的答案

构造函数(私有的_cdr:ChangeDetectorRef){
changeStatus():无效{
设置超时(()=>{
this.status=true;
此._cdr.detectChanges()
}, 1500);
}

我想你不需要这个。\u cdr.detectChanges()因为setTimeout已经进行了角度运行变化检测