【问题标题】:TypeScript | JavaScript | Angular 2: Dynamically Set @HostListener Argument打字稿 | JavaScript | Angular 2:动态设置@HostListener 参数
【发布时间】:2017-06-27 21:37:25
【问题描述】:

动态设置@HostListener 的参数

我有一个指令需要监听工程师以声明方式提供的任何事件。这是一个例子:

import { Directive, Input, ElementRef, HostListener, OnInit } from '@angular/core';
//--
import { Sandbox } from '../../../sandbox';

@Directive({ selector: '[addItem]' })
class AddNewItemDirective implements OnInit {
    @Input('addItem') data;
    @Input() on: string = 'click';

    constructor(private $: Sandbox, private element: ElementRef) { }
    ngOnInit() { console.log('@INIT', this); }

    @HostListener('click', ['$event']) handleEvent(e) {
        console.log('add-item', e);
    }
}

export { AddNewItemDirective };

这是它的用法:

<button class="btn btn-primary" [addItem]="{ name: 'Jeffrey' }" on="focus">Add New Item</button>

这很好用。但是,我的直觉告诉我,我应该能够在渲染时根据输入参数动态设置 HostListener 的参数:

@Directive({ selector: '[addItem]' })
class AddNewItemDirective implements OnInit {
    @Input('addItem') data;
    @Input() on: string = 'click';

    constructor(private $: Sandbox, private element: ElementRef) { }
    ngOnInit() { console.log('@INIT', this); }

    @HostListener(this.on, ['$event']) handleEvent(e) {
        console.log('add-item', e);
    }
}

当然,在调用 ngOnInit 之前,this.on 不会被 'focus' 覆盖。 令我惊讶this.on 引发错误,因为undefined has no property 'on'。因此,当我的指令类被实例化时,无论出于何种原因,this === undefined.

我发现了一个类似的问题here,不过,它希望在 runtime 时动态修改 HostListener,而我只需要在 compile/render/instantiation 时对其进行修改。

有人可以说明我如何做到这一点吗?

谢谢

【问题讨论】:

    标签: javascript angular typescript angular-directive event-listener


    【解决方案1】:

    HostListener 不是动态的,不能在运行时更改。你应该使用Renderer 类,它提供了listen 方法:

    @Input()
    public on:string;
    private dispose:Function;
    
    constructor(private renderer:Renderer, private elementRef:ElementRef){}
    
    ngOnInit(){
        this.dispose = this.renderer.listen(this.elementRef.nativeElement, this.on, e => console.log(e));
    }
    
    ngOnDestroy(){
         this.dispose();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 2018-04-15
      • 2016-10-29
      • 2017-11-21
      • 1970-01-01
      • 2017-09-24
      • 2016-12-07
      • 2017-04-14
      相关资源
      最近更新 更多