简体   繁体   English

如何在 angular 的回调 function 中访问组件 class 变量?

[英]How to access component class variables inside a callback function in angular?

In my component I have subscribed to html click event using addEventListener passed the callback function.在我的组件中,我订阅了 html 点击事件,使用addEventListener传递了回调 function。 Inside the call back function I used a component variable like this this.someVariable , but I saw the scope of this has been changed and set to the html element object. Inside the call back function I used a component variable like this this.someVariable , but I saw the scope of this has been changed and set to the html element object. Here how can I use component variables?在这里如何使用组件变量? Below I have given a sample code.下面我给出了一个示例代码。 Here inside my handleHtmlClickEvent() function I can't access the this.x variable.在我的handleHtmlClickEvent() function 里面,我无法访问this.x变量。

export class SomeComponent implements OnInit, AfterViewInit{
   x = 'Hello';
   constructor(private elementRef: ElementRef){}
   ngOnInit(){
   }
   ngAfterViewInit(){
     const element = this.elementRef.nativeElement.getByElementId('123');
     element.addEventListener('click', this.handleHtmlClickEvent)
   }
   handleHtmlClickEvent(){
     console.log(this.x);
   }
}

Do not touch the DOM directly.不要直接接触 DOM。 It's a bad practice to do it like that.这样做是不好的做法。

Use ViewChild decorator or create a directive.使用ViewChild装饰器或创建指令。

Solution 1 - ViewChild解决方案 1 - ViewChild

In your html template assign a template variable to the element that you want to target:在您的 html 模板中,将模板变量分配给您要定位的元素:

<div #element></div>

In your component:在您的组件中:

export class SomeComponent implements OnInit, AfterViewInit{
   x = 'Hello';
   @ViewChild('element') element: ElementRef<HTMLDivElement>;

   // use @HostListener decorator to attach your listener
   @HostListener('click', ['$event'])
   onClick(event: MouseEvent) {
    if (event.target === this.element.nativeElement) {
      console.log(this.x);
    }
  }
}

Solution 2 - Directive解决方案 2 - 指令

@Directive({
  selector: '[appSomeDirective]'
})
export class SomeDirective {
   // use the Input decorator to display the message
   @Input() message: string;

   constructor(private elementRef: ElementRef){}

   @HostListener('click', ["$event"])
   onClick(event: MouseEvent) {
     console.log(this.message);
  }
}

In your component template:在您的组件模板中:

<div appSomeDirective [message]="x"></div>

If you want to manipulate the element or elements use the Render2 service.如果要操作元素或元素,请使用Render2服务。

Update更新

For the case described in your comment you can do something like below:对于您评论中描述的情况,您可以执行以下操作:

 x = 'Hello';
 @ViewChild('element') element: ElementRef<HTMLDivElement>;

 constructor(private renderer: Renderer2) {}

 ngAfterViewInit() {
    const links = this.element.nativeElement.querySelectorAll('a');

    links.forEach(link =>
      // use the Renderer2 service to start an event listener 
      this.renderer.listen(link, 'click', (event: MouseEvent) => {
        console.log(this.x);
        ...
      })
    );
  }

While the implementation above will work, I'm not sure how performant it will be if you have dozens or hundreds of links.虽然上面的实现可以工作,但如果你有几十个或几百个链接,我不确定它的性能如何。

Assign scope to your click event将 scope 分配给您的点击事件

element.addEventListener('click', this.handleHtmlClickEvent.bind(this))

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

相关问题 如何在发出的 Highcharts 选择事件回调函数中获取角度组件类引用? - How to get the angular component class reference inside an emitted Highcharts selection event callback function? 如何访问 JavaScript 事件回调函数内的变量? - How to access variables that are inside a callback function of a JavaScript event? 在anime.js的回调函数中访问Angular组件属性/ function - Access Angular component property/ function inside callback functions of anime.js Angular 2-在内部函数中使用组件变量 - Angular 2 - using component variables inside inner function 如何在回调函数的Angular 1.5组件中处理此问题? - How to handle this in Angular 1.5 component in callback function? 如何从回调函数访问外部变量? - How to access outer variables from a callback function? Angular2中回调函数内的范围变量的访问值 - Access value of the scope variable inside callback function in Angular2 回调函数访问闭包变量? - callback function access to closure variables? 如何从Angular中的回调访问外部作用域变量? - How do I access outer scope variables from a callback in Angular? 从React中父组件的回调函数中的子组件访问变量,并在父组件中呈现返回的值 - Access variables from a child component in parent component's callback function in React and render the returned value in parent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM