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. Golang之并发资源竞争(互斥锁)

    并发本身并不复杂,但是因为有了资源竞争的问题,就使得我们开发出好的并发程序变得复杂起来,因为会引起很多莫名其妙的问题. package main import ( "fmt" &q ...

  2. 使用Redis进行简单的数据缓存

    引入spring-data-redis包.jedis.connection-pool包 applicationContext.xml的配置 <!-- redis Connection --> ...

  3. 十一、curator recipes之联锁InterProcessMultiLock

    简介 curator实现了一个类似容器的锁InterProcessMultiLock,它可以把多个锁包含起来像一个锁一样进行操作,简单来说就是对多个锁进行一组操作.当acquire的时候就获得多个锁资 ...

  4. memcached 细究(一)

    memcached是高性能的分布式的内存缓存服务器.由国外社区网站LIVEJOURNAL的开发团队开发. 使用目的: 通过缓存数据库查询结果,减少数据库的访问次数,以提高动态web应用的速度.提高可扩 ...

  5. Mybatis之简单注解

    Mybatis使用注解实现主键自增长: oracle: @SelectKey(statement="select my_seq.nextval from dual",resultT ...

  6. 理解ResourceBundle.getBundle("dataSourceFactory")

    最近在项目文件中看到这样的代码一下子还看不懂 经过他人指点和自己百度,总算明白大致用处. 首先这个方法时java.util的内置方法,主要功能是用于解析properties文件的. ResourceB ...

  7. Centos的一个find命令配合rm删除某天前的文件

    语句写法:find 对应目录 -mtime +天数 -name "文件名" -exec rm -rf {} \; 例1: 将/usr/local/backups目录下所有10天前带 ...

  8. web 开发人员必须学习的 3 门语言

    web 开发人员必须学习的 3 门语言:html  css  js HTML 定义了网页的内容 CSS 描述了网页的布局 JavaScript 网页的行为

  9. UOJ188. 【UR #13】Sanrd

    传送门 Sol 设 \(f_i\) 表示 \(i\) 的次大质因子 题目就是要求 \[\sum_{i=l}^{r}f_i\] 考虑求 \(\sum_{i=1}^{n}f_i\) 所求的东西和质因子有关 ...

  10. display:table和display:table-cell的妙用

    display的table和table-cell一般情况下用的不多,所以很少有人去关注它,但他们两个联手起来会给你惊喜! 这里抛出这样一个问题,如下,让块里的多行文字垂直居中?一说到垂直居中就会想到, ...