host属性

@Component({

selector: 'jhi-project',

templateUrl: './project.html',

styleUrls: [],

host: { '(window:keydown)': 'keyboardInput($event)' }    //绑定事件和方法

})

export class JhiProjectComponent {

keyboardInput(event) {

if (event.keyCode == 65 && event.ctrlKey) {

// ctrl + a

....

}

}

}

@HostListener

HostListener是属性装饰器,用来为宿主元素添加事件监听。

定义:

// HostListenerDecorator的定义
export interface HostListenerDecorator {
(eventName: string, args?: string[]): any;
new (eventName: string, args?: string[]): any;
}

应用:

// counting.directive.ts
import { Directive, HostListener } from '@angular/core'; @Directive({
selector: 'button[counting]'
})
class CountClicks {
numberOfClicks = ; @HostListener('click', ['$event.target'])
onClick(btn: HTMLElement) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}

app.component.ts

import { Component} from '@angular/core';

@Component({
selector: 'exe-app',
styles: [`
button {
background: blue;
color: white;
border: 1px solid #eee;
}
`],
template: `
<button counting>增加点击次数</button>
`
})
export class AppComponent {}

以上代码运行结果:

此外,还可以监听宿主元素外,其他对象产生的事件,如windown或document对象。

highlight.directive.ts

import { Directive, HostListener, ElementRef, Renderer } from '@angular/core';

@Directive({
selector: '[exeHighlight]'
})
export class ExeHighlight {
constructor(private el: ElementRef, private renderer: Renderer) { } @HostListener('document:click', ['$event'])
onClick(btn: Event) {
if (this.el.nativeElement.contains(event.target)) {
this.highlight('yellow');
} else {
this.highlight(null);
}
} highlight(color: string) {
this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
}
}
import {HostListener} from '@angular/core';

@HostListener('window:keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
...
}

app.component.ts

import { Component} from '@angular/core';

@Component({
selector: 'exe-app',
template: `
<h4 exeHighlight>点击该区域,元素会被高亮。点击其它区域,元素会取消高亮</h4>
`
})
export class AppComponent {}

也可以在指定的metadata信息中,设定宿主元素的事件监听信息,示例:

counting.directive.ts

import { Directive } from '@angular/core';

@Directive({
selector: 'button[counting]',
host: {
'(click)': 'onClick($event.target)'
}
})
export class CountClicks {
numberOfClicks = ; onClick(btn: HTMLElement) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}

@HostBinding

HostBinding 是属性装饰器,用来动态设置宿主元素的属性值。

定义:

export interface HostBindingDecorator {
(hostPropertyName?: string): any;
new (hostPropertyName?: string): any;
}

应用:

@HostBindings('attr.foo') foo = 'bar'

button-press.directive.ts

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
selector: '[exeButtonPress]'
})
export class ExeButtonPress {
@HostBinding('attr.role') role = 'button';
@HostBinding('class.pressed') isPressed: boolean; @HostListener('mousedown') hasPressed() {
this.isPressed = true;
}
@HostListener('mouseup') hasReleased() {
this.isPressed = false;
}
}

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'exe-app',
styles: [`
button {
background: blue;
color: white;
border: 1px solid #eee;
}
button.pressed {
background: red;
}
`],
template: `
<button exeButtonPress>按下按钮</button>
`
})
export class AppComponent { }

我们也可以在指令的 metadata 信息中,设定宿主元素的属性绑定信息,具体示例如下:

button-press.directive.ts

import { Directive, HostListener } from '@angular/core';

@Directive({
selector: '[exeButtonPress]',
host: {
'role': 'button',
'[class.pressed]': 'isPressed'
}
})
export class ExeButtonPress {
isPressed: boolean; @HostListener('mousedown') hasPressed() {
this.isPressed = true;
}
@HostListener('mouseup') hasReleased() {
this.isPressed = false;
}
}

Angular4 @HostBinding @HostListener的更多相关文章

  1. Angular @HostBinding()和@HostListener()用法

    @HostBinding()和@HostListener()在自定义指令时非常有用.@HostBinding()可以为指令的宿主元素添加类.样式.属性等,而@HostListener()可以监听宿主元 ...

  2. Angular 2 HostListener & HostBinding

    原文 https://www.jianshu.com/p/20c2d60802f7 大纲 1.宿主元素(Host Element) 2.HostListener 3.HostListenerDecor ...

  3. Angular6在自定义指令中使用@HostBingDing() 和@HostListener()

    emmm,,,最近在为项目的第二阶段铺路,偶然看到directive,想想看因为项目已经高度集成了第三方组件,所以对于自定义指令方面的经验自己实在知之甚少,后面经过阅读相关资料,总结一篇关于在自定义指 ...

  4. Angular2 - Starter - Component and Component Lifecircle Hooks

    我们通过一个NgModule来启动一个ng app,NgModule通过bootstrap配置来指定应用的入口组件. @NgModule({ bootstrap: [ AppComponent ], ...

  5. Angular动画

    Angular动画基于W3C的Web Animations标准.不在Angular Core中了. 组件里面定义一个或多个触发器trigger,每个触发器有一系列的状态和过渡效果来实现. 动画其实就是 ...

  6. AngularJS2+调用原有的js脚本(AngularJS脚本跟本地原有脚本之间的关系)

    昨天一个话题说关于AngularJS2以后版本的两个小技巧,不料引出了另外一个话题,话题起始很简单: "很多的前端框架并不复杂,比如JQuery,引入即用,实时看到效果,多好.到了Angul ...

  7. angular5自适应窗口大小

    import {AfterViewInit, Directive, ElementRef, HostBinding, HostListener, Inject, Input, Renderer2} f ...

  8. Angular开发规范

    目录  一.         前言 1.1.       规范目的 1.2.       局限性 二.         文件规范 2.1.       文件结构约定 2.2.       单一职责原则 ...

  9. angular实现draggable拖拽

    前言:最近项目要实现一个拖拽功能,我在网上开始了各类搜寻,虽然后面因为数据原因舍弃了拖拽的这一需求,但是为了不辜负最近的研究,还是来记录一下. 场景需求:面试预约选时间节点,候选人之间是可以相互交换的 ...

随机推荐

  1. JSONP数据调用

     json 是一种数据格式  jsonp 是一种数据调用的方式. 什么是JSONP          为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是 ...

  2. 转换json和字符串的一些方法

    将字符串转换成json对象的方法: var str = '{"name1":"value1","name2":"value2&qu ...

  3. vue-cli 中遇见的问题,记录爬坑日常!

    本片文章我将会记录使用vue-cli 以及一些相关插件遇见的问题和解决方案,另外本文章将会持续更新,本着互联网分享精神,希望我所记录的日常能对大家有所帮助. 1.在img和html文件处于同级阶段,i ...

  4. php分页实例及其原理

    Part1:实例 /** * 取得上次的过滤条件 * @param string $param_str 参数字符串,由list函数的参数组成 * @return 如果有,返回array('filter ...

  5. FisherYates费雪耶兹随机置乱算法

    public class FisherYates { public static void main(String[] args) { int[] arr = new int[10]; // 初始有序 ...

  6. MongoDB客户端及监控工具

    现在许多应用都使用MongoDB存储大量的业务数据,MongoDB基于文档式的存储,在大数据行业的应用还是很普遍的.MongoDB的客户端工具也很多,基于web的却不多,国产的就更少了,下面这款国产的 ...

  7. springcloud 实战 feign使用中遇到的相关问题

    springcloud 实战 feign使用中遇到的相关问题 1.使用feign客户端调用其他微服务时,session没有传递成功,sessionId不一样. /** * @author xbchen ...

  8. [HAOI2009]逆序对数列(加强)

    ZJL 的妹子序列 暴力就是 \(\Theta(n\times m)\) 如果 \(n,m \le 10^5\) ? 考虑问题的转换,设 \(a_i\) 表示 \(i\) 小的在它后面的数的个数 \( ...

  9. FCC的javascript初级算法题解答

    FCC上的javascript基础算法题 前一阵子做的基础算法题,感觉做完后收获还蛮大的,现在将自己的做法总结出来,供大家参考讨论.基本上做到尽量简短有效,但有些算法还可以继续简化,比如第七题若采用正 ...

  10. C# Timer定时器用法

    System.Timers.Timer timer1 = new System.Timers.Timer(); timer1.Elapsed += new System.Timers.ElapsedE ...