简体   繁体   English

如何在angular2打字稿的组件中获取变量“ this”的集合?

[英]How do I get a set “this” to a variable in a component in angular2 typescript?

I have a component. 我有一个组件。 Inside I have the following: 在内部,我有以下内容:

constructor() {
  this.something = "Hello";
}

document.addEventListener('click', doSomething());

function doSomething(e) {
   console.log(this.something) // this is undefined
}

I want to make it so that I can access this.something inside of the doSomething(e). 我想要这样做,以便可以访问doSomething(e)内部的this.something。 Usually I would just create a variable outside and use var self = this; 通常我只是在外部创建一个变量,然后使用var self = this; then reference self.something to get to that "Hello". 然后引用self.something进入该“ Hello”。 Unfortunately in angular 2, I am getting errors with self not being defined, etc. How can I access this.something inside of the event listener I created? 不幸的是,在角度2中,我收到未定义self的错误,等等。如何在我创建的事件侦听器内部访问this.something?

您应该使用lambda函数来更正此问题

document.addEventListener('click', () => doSomething());

Another option with Angular, instead of adding an event listener to the document directly, is the @HostListener function decorator. @HostListener函数装饰器是Angular的另一种选择,而不是直接将事件侦听器添加到文档中。 Below is a sample. 下面是一个示例。 More information . 更多信息

@HostListener('click', ['$event'])
onClick(event) : void {

    event.stopPropagation();

    if(...) {
        console.log(this.something);
    }
    else if (...) {
        ...
    }
}

Obviously, I don't know your whole situation, but something like this could be of use to you. 显然,我不了解您的整体情况,但是类似的事情可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM