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拖拽
前言:最近项目要实现一个拖拽功能,我在网上开始了各类搜寻,虽然后面因为数据原因舍弃了拖拽的这一需求,但是为了不辜负最近的研究,还是来记录一下. 场景需求:面试预约选时间节点,候选人之间是可以相互交换的 ...
随机推荐
- 基础语言知识JAVA
1. 总结: JAVA比较重要的博客: http://www.runoob.com/java/java-tutorial.html (JAVA教程) http://blog.csdn.net/ ...
- C C++ OC指针常量和常量指针区别
看Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法这本书的时候看到有一个说多用类型常量,少用#define预处理指令 ,在这里面有说到指针常量,之前 ...
- Angular 应用中的登陆与身份验证
Angular 经常会被用到后台和管理工具的开发,这两类都会需要对用户进行鉴权.而鉴权的第一步,就是进行身份验证.由于 Angular 是单页应用,会在一开始,就把大部分的资源加载到浏览器中,所以就更 ...
- C# 通过反射获取方法/类上的自定义特性
1.所有自定义属性都必须继承System.Attribute 2.自定义属性的类名称必须为 XXXXAttribute 即是已Attribute结尾 自定义属性QuickWebApi [Attribu ...
- js判断向量叉点 并求出交点坐标
代码如下可以直接运行,判断向量相交并求出交点坐标 <!DOCTYPE html> <html> <head> <meta http-equiv=" ...
- var、let、const的区别,以及作用范围。
在es5中一般经常使用的变量有两个级别,一个是用var声明的全局级别的变量,另外一个是函数级别是用var生命在函数内的.本文中将详细讲解我对es6中的const和let的区别. let的使用以及作用范 ...
- yum卸载
完全卸载依赖 -- 正常安装 yum install sl -- 列出操作 yum history list sl -- 根据显示install操作的id进行删除 yum history undo { ...
- Sprng IOC&AOP&事务梳理 (文章整理new)
IOC <理解 IOC> <IOC 的理解与解释> 正向控制:传统通过new的方式.反向控制,通过容器注入对象. 作用:用于模块解耦. DI:Dependency Inject ...
- java.lang.StackOverflowError: null
异常信息 java.lang.StackOverflowError: null at sun.misc.FloatingDecimal$BinaryToASCIIBuffer.dtoa(Floatin ...
- QQ 聊天机器人小薇 2.1.0 发布!
本次发布加入了支持茉莉机器人,并且更容易搭建开发环境,在线显示登录二维码~ 简介 XiaoV(小薇)是一个用 Java 写的 QQ 聊天机器人 Web 服务,可以用于社群互动: 监听多个 QQ 群消息 ...