首页 > 解决方案 > Updating value of a variable and ViewChild ElementRef is not working inside setTimeOut() function in .TS file

问题描述

I am working on an Angular project. I am using loader in the project.

app.html

<div #loading>
  <app-loader></app-loader>
</div>

app.ts

@ViewChild('loading', {static:false}) loading:ElementRef;

If I use the code below, It is working absolutely fine. Console is printing the element.

ngAfterViewInit() {
  console.log(this.loading.nativeElement);
}

But if I use it inside the setTimeOut() function, In the console I am getting its value as undefined.

ngAfterViewInit() {
 setTimeout(function () {
   console.log(this.loading.nativeElement);
  }, 1000);
}

Why is this so, I am not getting it inside setTimeOut() function. If I use a variable loading=false and if I update it inside setTimeOut() function as setTimeout(function() {this.loading=false;}, 1000); the value of loading still not updating there.

I also can use document.getElementById('loading') in JavaScript or $("#loading").css("display", "none"); in JQuery. But I don't have to. I want to use it only in type script, neither in java script nor in JQuery.

Please let me know If any one know the way to access an element in setTimeOut() function in pure Typescript.

标签: typescriptangular8

解决方案


Youll want to use "fat arrow function" syntax instead. It does not create it's own bindings to this, which allows you to access variables in your component easily.

ngAfterViewInit() {
 setTimeout(() => {
   console.log(this.loading.nativeElement);
  }, 1000);
}

推荐阅读