【问题标题】:How to assign event to variable in typescript如何将事件分配给打字稿中的变量
【发布时间】:2020-02-07 21:18:36
【问题描述】:

试图在变量中分配事件但不起作用。我不知道如何分配。我进入 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

【问题讨论】:

  • 有什么问题?
  • @VLAZ:如何将事件保存在变量中
  • 但是你这里的代码有什么问题?什么不起作用?你有任何错误吗?你有意外的行为吗?你期望的行为是什么?说“不起作用”对于试图确定问题所在以及如何解决问题没有帮助。
  • @VLAZ:编辑了我的问题..我得到 this.myEvents 为空

标签: typescript angular6 angular7 angular8


【解决方案1】:

在您的模板文件中,

使用

<button (click)="logEvent($event)">Set event</button>

代替

<button (click)="logEvent(e)">Set event</button>

也许对你有帮助。

【讨论】:

  • 该死的我没看到。
【解决方案2】:

您必须在 setInterval () =&gt; 中使用箭头函数,否则 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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多