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. 对数几率回归法(梯度下降法,随机梯度下降与牛顿法)与线性判别法(LDA)

    本文主要使用了对数几率回归法与线性判别法(LDA)对数据集(西瓜3.0)进行分类.其中在对数几率回归法中,求解最优权重W时,分别使用梯度下降法,随机梯度下降与牛顿法. 代码如下: #!/usr/bin ...

  2. HDFS Java Client对hdfs文件增删查改

      step1:增加依赖 pom.xml           ...      <!-- https://mvnrepository.com/artifact/org.apache.hadoop ...

  3. 【angular5 项目积累总结】项目公共样式

    main.css @font-face { font-family: 'wf_segoe-ui_normal'; src: local('Segoe UI'),url('../fonts/segoe- ...

  4. Linq学习以及简单用法

    Linq学习 Linq(language Intergrated Query)即语言集成查询 LINQ是一组语言特性和API,使得你可以使用统一的方式编写各种查询.用于保存和检索来自不同数据源的数据, ...

  5. JS获取当前屏幕宽高

    Javascript: 网页可见区域宽: document.body.clientWidth网页可见区域高: document.body.clientHeight网页可见区域宽: document.b ...

  6. MySQL查询小数点位数

    怎么查询某个字段中小数有几位? MySQL数据库: 通过下面sql就可以查出来,有2位col*100,有3位col*1000,一次类推: ) 备注:floor:函数只返回整数部分,小数部分舍弃. Or ...

  7. ZOJ Problem Set - 2818

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1818 一开始想着用循环做,看了别人的解法才发现根本没必要,比较根号n就行了 # ...

  8. protobuf版本冲突

    在编译chromium代码的过程中发现,官方推荐使用的版本是ubuntu16.04,但是这个版本的ubuntu比较老旧,一些库都比较老了,但是google自己用的部分却是挺新的,protobuf就是一 ...

  9. MYSQL建表问题(转)

    今天在dos下准备新建一个数据表,但一直出错,如下 后面在网上查了好久,终于找到了原因.创建 MySql 的表时,表名和字段名外面的符号 ` 不是单引号,而是英文输入法状态下的反单引号,也就是键盘左上 ...

  10. BZOJ4833: [Lydsy1704月赛]最小公倍佩尔数

    Problem 传送门 Sol 容易得到 \[f_n=e_{n-1}+f_{n-1},e_{n-1}=f_{n-1}+e_{n-1},f_1=e_1=1\] 那么 \[f_n=2\times \sum ...