Angular2 hostlistener

时间:2016-03-09 13:47:16

标签: angular

如何让HostListener在优秀的旧版ES6中工作。目前有......

import { Directive, HostListener }                from 'angular2/core';

@Directive({
    selector: 'focusable',
    hostListeners: {
        'focus' : 'focus()',
        'click' : 'click()'
    }
})
export class FocusableComponent {
    constructor(){
        console.log('constructed');
    }

    focus() {
        console.log('Im focused');
    }

    click() {
        console.log('ive been clicked');
    }
}

从我可以从文档中得到的结果......这似乎是人们如何做到的,但不适合我!

1 个答案:

答案 0 :(得分:2)

你应该这样做:

@Directive({
  selector: '[focusable]',
  host: {
    '(focus)' : 'focus()',
    '(click)' : 'click()'
  }
})
export class FocusableComponent {
  constructor(){
    console.log('constructed');
  }

  focus() {
    console.log('Im focused');
  }

  click() {
    console.log('ive been clicked');
  }
}

请参阅此plunkr:https://plnkr.co/edit/pBxcqP25JTLTzKY2AwyP?p=preview