typescript - 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.
解决方案
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);
}
推荐阅读
- powershell - *$($name.text)* 不起作用你能解释一下吗?
- python - scipy.stats.lognorm.interval 的倒数
- omnipay - Omnipay 返回一个空的 Itembag
- rabbitmq - 监听 RabbitMQ 服务器启动
- ios - iOS WebRTC 连接卡在 Ice Connection State Gathering
- android - 为 GridView 创建适配器时的内部类构造函数问题
- python-3.x - 如何在linux build for windows10主机上构建python3.7
- java - 尝试@Override addViewControllers() 方法时出现问题 - Spring Security
- python - 从列表列表中选择特定位置的项目
- python - 使用 while 循环的 Runge Kutta 算法