[英]How to assign event to variable in typescript
试图在变量中分配一个事件但不起作用。我不知道如何分配。我进入 console.log(this.myEvents) 就像 null 一样,但无法访问最近的 tr。 如果有人知道,请帮助找到解决方案。
app.component.ts:
public myEvents:any;
logEvent(e)
{
this.myEvents=e; // Store event info
}
// Set a timer for looping through the events
gameTimer = setInterval(function() {
// Loop through events
if(this.myEvents)
{
console.log(this.myEvents);// getting null
}
}, 100)
app.component.html:
<button (click)="logEvent(e)">Set event</button>
演示: https : //stackblitz.com/edit/angular-yqelod?file= src/ app/app.component.ts
您必须在 setInterval () =>
使用箭头函数,否则this
指针未显示在您的组件上并且您无法分配给this.myEvents
。
我在没有测试的情况下修复了您的组件:
class Game implements OnInit, OnDestroy {
public myEvents: any;
private gameTimer: any = null;
constructor() {
}
// Set a timer for looping through the events
ngOnInit() {
this.gameTimer = setInterval(() => {
// Loop through events
if (this.myEvents) {
console.log(this.myEvents);// getting null
}
}, 100);
}
ngOnDestroy() {
if (this.gameTimer !== null) {
clearInterval(this.gameTimer);
}
}
logEvent(e: any)
{
this.myEvents = e; // Store event info
}
}
重要的是部分:
this.gameTimer = setInterval(() => {
// Loop through events
if (this.myEvents) {
console.log(this.myEvents);// getting null
}
}, 100);
更新:工作 stackblitz 示例: https ://stackblitz.com/edit/angular-xcjuqn
在您的模板文件中,
用
<button (click)="logEvent($event)">Set event</button>
代替
<button (click)="logEvent(e)">Set event</button>
它可能会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.