Angular4 @HostBinding @HostListener
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的更多相关文章
- Angular @HostBinding()和@HostListener()用法
@HostBinding()和@HostListener()在自定义指令时非常有用.@HostBinding()可以为指令的宿主元素添加类.样式.属性等,而@HostListener()可以监听宿主元 ...
- Angular 2 HostListener & HostBinding
原文 https://www.jianshu.com/p/20c2d60802f7 大纲 1.宿主元素(Host Element) 2.HostListener 3.HostListenerDecor ...
- Angular6在自定义指令中使用@HostBingDing() 和@HostListener()
emmm,,,最近在为项目的第二阶段铺路,偶然看到directive,想想看因为项目已经高度集成了第三方组件,所以对于自定义指令方面的经验自己实在知之甚少,后面经过阅读相关资料,总结一篇关于在自定义指 ...
- Angular2 - Starter - Component and Component Lifecircle Hooks
我们通过一个NgModule来启动一个ng app,NgModule通过bootstrap配置来指定应用的入口组件. @NgModule({ bootstrap: [ AppComponent ], ...
- Angular动画
Angular动画基于W3C的Web Animations标准.不在Angular Core中了. 组件里面定义一个或多个触发器trigger,每个触发器有一系列的状态和过渡效果来实现. 动画其实就是 ...
- AngularJS2+调用原有的js脚本(AngularJS脚本跟本地原有脚本之间的关系)
昨天一个话题说关于AngularJS2以后版本的两个小技巧,不料引出了另外一个话题,话题起始很简单: "很多的前端框架并不复杂,比如JQuery,引入即用,实时看到效果,多好.到了Angul ...
- angular5自适应窗口大小
import {AfterViewInit, Directive, ElementRef, HostBinding, HostListener, Inject, Input, Renderer2} f ...
- Angular开发规范
目录 一. 前言 1.1. 规范目的 1.2. 局限性 二. 文件规范 2.1. 文件结构约定 2.2. 单一职责原则 ...
- angular实现draggable拖拽
前言:最近项目要实现一个拖拽功能,我在网上开始了各类搜寻,虽然后面因为数据原因舍弃了拖拽的这一需求,但是为了不辜负最近的研究,还是来记录一下. 场景需求:面试预约选时间节点,候选人之间是可以相互交换的 ...
随机推荐
- vue+webpack项目中使用dev-server搭建虚拟服务器,请求json文件数据,实现前后台分离开发
在项目开发中,前后台分离,做了假数据,项目使用vue2.0重构,后台也推到重来了,为了不耽误开发进程,我做了虚拟的数据请求,使用vue-cli脚手架搭建的项目文件中dev-server搭建虚拟api请 ...
- BigDecimal 精准加减乘除
解决了double和float精确度的问题 Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算.双精度浮点型变量double可以处理16位有效 ...
- java.sql.SQLException: Io 异常: Invalid number format for port number
java.sql.SQLException: Io 异常: Invalid number format for port number jdbc数据库链接配置没有写端口号 要检查jdbc的配置 ...
- groovy动态类型--能力式设计
动态类型 动态类型中的类型是在运行时推断的,方法及其参数也是在运行时检查的. 能力式设计 被称作鸭子模式:他有这么一个观点:如果它走路像鸭子,叫起来也像鸭子,那么他就是一只鸭子. 契约式设计 相当于J ...
- bash shell学习笔记(一)—— 常用命令
一.基本的bash shell命令 1.默认bash shell 提示符是美元符号($); 2.bash手册 使用man命令来访问存储在Linux系统上的手册页面,如: bogon:~ Mac$ ma ...
- SqlServer代理(已禁用代理xp)
SqlServer 本地库作业管理的时候已禁用,将其修改为可使用,master数据库下执行以下语句: sp_configure 'show advanced options', 1; GO REC ...
- 51NOD1847:奇怪的数学题
传送门 Sol 设 \(f(d)\) 表示 \(d\) 所有约数中第二大的,\(low_d\) 表示 \(d\) 的最小质因子 \[f(d)=\frac{d}{low_d}\] 那么 \[\sum_{ ...
- WC前的颓废——带花树
QAQ现在很不想写题解博客那就来写个算法吧QAQ... 带花树 题目 来看个题... UOJ79. 某机房里有\(n\)个OIer,其中有\(n\)个男生,\(0\)个女生.现在他们要两两配对. 有\ ...
- BZOJ5068: 友好的生物(状压 贪心)
题意 题目链接 Sol 又是一道神仙题??.. 把绝对值拆开之后状压前面的符号?.. 下界显然,但是上界为啥是对的呀qwq.. #include<bits/stdc++.h> using ...
- Android LinkedList和ArrayList的区别
LinkedeList和ArrayList都实现了List接口,但是它们的工作原理却不一样.它们之间最主要的区别在于ArrayList是可改变大小的数组,而LinkedList是双向链接串列(doub ...