加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角色2:主机绑定和主机侦听

发布时间:2020-12-17 07:47:07 所属栏目:安全 来源:网络整理
导读:如何使用主机侦听器和主机绑定在angularjs 2? 我尝试这样做主机监听器,但总是显示“声明预期”错误. app.component.ts: import {Component,EventEmitter,HostListener,Directive} from 'angular2/core';@Directive({ selector: 'button[counting]'})class
如何使用主机侦听器和主机绑定在angularjs 2?
我尝试这样做主机监听器,但总是显示“声明预期”错误.

app.component.ts:

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

@Directive({
    selector: 'button[counting]'
})

class HostSample {
    public click = new EventEmitter();
    @HostListener('click',['$event.target']);
    onClickBtn(btn){
        alert('host listener');
    }
}

@Component({
    selector: 'test',template: '<button counting></button>',directives: [HostSample]
})

export class AppComponent {
   constructor(){
   }
}
@HostListener是回调/事件处理程序方法的装饰器,因此删除;在这行结尾:
@HostListener('click',['$event.target']);

这是通过复制API docs中的代码生成的plunker,但是为了清楚起见,我将onClick()方法放在同一行上:

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

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click',['$event.target']) onClick(btn) {
    console.log("button",btn,"number of clicks:",this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',template: `<button counting>Increment</button>`,directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

主机绑定也可以用来监听全局事件. “要听全球事件,必须在事件名称中添加一个目标,目标可以是窗口,文档或正文”(reference):

@HostListener('document:keyup',['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读