Angular 2 HostListener & HostBinding
原文
https://www.jianshu.com/p/20c2d60802f7
大纲
1、宿主元素(Host Element)
2、HostListener
3、HostListenerDecorator 装饰器应用
4、HostBinding
5、HostBinding 装饰器应用
宿主元素(Host Element)
在介绍 HostListener 和 HostBinding 属性装饰器之前,我们先来了解一下 host element (宿主元素)。
宿主元素的概念同时适用于指令和组件。对于指令来说,这个概念是相当简单的。应用指令的元素,就是宿主元素。假设我们已声明了一个 HighlightDirective 指令 (selector: '[exeHighlight]'):
<p exeHighlight>
<span>高亮的文本</span>
</p>
上面 html 代码中,p 元素就是宿主元素。如果该指令应用于自定义组件中如:
<exe-counter exeHighlight>
<span>高亮的文本</span>
</exe-counter>
此时 exe-counter 自定义元素,就是宿主元素。
HostListener
HostListener 是属性装饰器,用来为宿主元素添加事件监听。
/*
HostListenerDecorator 装饰器定义
*/
export interface HostListenerDecorator {
(eventName: string, args?: string[]): any;
new (eventName: string, args?: string[]): any;
}
HostListenerDecorator 装饰器应用
/*
counting.directive.ts
*/
import { Directive, HostListener } from '@angular/core'; @Directive({
selector: 'button[counting]'
})
class CountClicks {
numberOfClicks = 0; @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 {} /*
以上代码运行后浏览器显示的结果:
*/
此外,我们也可以监听宿主元素外,其它对象产生的事件,如 window 或 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);
}
} /*
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 = 0; onClick(btn: HTMLElement) {
console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}
HostBinding
HostBinding 是属性装饰器,用来动态设置宿主元素的属性值。
/*
HostBinding 装饰器定义
*/
export interface HostBindingDecorator {
(hostPropertyName?: string): any;
new (hostPropertyName?: string): any;
}
HostBinding 装饰器应用
/*
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 { } /*
以上代码运行后浏览器显示的结果:
*/
Host Property Bindings
我们也可以在指令的 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;
}
}
宿主元素属性和事件绑定风格指南
优先使用 @HostListener 和 @HostBinding ,而不是 @Directive 和 @Component 装饰器的 host 属性。
对于关联到 @HostBinding 的属性或关联到 @HostListener 的方法,要修改时,只需在指令类中的一个地方修改。 如果使用元数据属性 host,你就得在组件类中修改属性声明的同时修改相关的元数据。
参考网址
https://segmentfault.com/a/1190000008878888
Angular 2 HostListener & HostBinding的更多相关文章
- [Angular Directive] Combine HostBinding with Services in Angular 2 Directives
You can change behaviors of element and @Component properties based on services using @HostBinding i ...
- Angular4 @HostBinding @HostListener
host属性 @Component({ selector: 'jhi-project', templateUrl: './project.html', styleUrls: [], host: { ' ...
- [Angular 2] Directive intro and exportAs
First, What is directive, what is the difference between component and directive. For my understandi ...
- Angular 4+ 修仙之路
Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...
- [Angular] Test Directive
directive: import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core'; @Direct ...
- [Angular Directive] 3. Handle Events with Angular 2 Directives
A @Directive can also listen to events on their host element using @HostListener. This allows you to ...
- [Angular] Using directive to create a simple Credit card validator
We will use 'HostListener' and 'HostBinding' to accomplish the task. The HTML: <label> Credit ...
- [转]angular 监听窗口滚动
本文转自:https://blog.csdn.net/ittvibe/article/details/80060801 转自:http://brianflove.com/2016/10/10/angu ...
- Angular @HostBinding()和@HostListener()用法
@HostBinding()和@HostListener()在自定义指令时非常有用.@HostBinding()可以为指令的宿主元素添加类.样式.属性等,而@HostListener()可以监听宿主元 ...
随机推荐
- C#打开SDE数据库的几种方式总结
转自谢灿软件原文 C#打开SDE数据库的几种方式总结 1.通过指定连接属性参数打开数据库 /// <param name="server">数据库服务器名</pa ...
- [Python] String Formatting
One particularly useful string method is format. The format method is used to construct strings by i ...
- iOS Dev (51)加急审核
https://developer.apple.com/appstore/contact/? topic=expedite
- vue.js有什么用,是用来做什么的(整理)
vue.js有什么用,是用来做什么的(整理) 一.总结 一句话总结:用数据绑定的思想,vue可以简单写单个页面,也可以写一个大的前端系统,也可以做手机app的界面. 1.Vue.js是什么? 渐进式框 ...
- 洛谷P1852 奇怪的字符串
题目描述 输入两个01串,输出它们的最长公共子序列的长度 输入输出格式 输入格式: 一行,两个01串 输出格式: 最长公共子序列的长度 输入输出样例 输入样例#1: 复制 01010101010 00 ...
- echarts tooltip提示框 自定义小圆点(颜色、形状和大小等等)
项目是拿 echarts + 百度地图 来做可视化界面,现在到收尾阶段慢慢优化. 先附代码: formatter: function(params) { var result = '' params. ...
- Centos下Elasticsearch安装详细教程
Centos下Elasticsearch安装详细教程 1.Elasticsearch简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于 ...
- IOS-Run loop学习总结
不知道大家有没有想过这个问题,一个应用開始执行以后放在那里,假设不正确它进行不论什么操作.这个应用就像精巧了一样,不会自发的有不论什么动作发生.可是假设我们点击界面上的一个button.这个时候就会有 ...
- Android触摸事件(五)-CropBitmapActivity关于裁剪工具的使用
文件夹 文件夹 概述 传递数据 裁剪流程 其他事项 使用方式 图片辅助功能 图片缩略图载入 图片旋转 源代码 GitHub地址 演示样例GIF 概述 这个Activity是为了裁剪图片的.使用时须要提 ...
- ASP.Net MVC Filter验证用户登录
一.Filter是什么 ASP.NetMVC模式自带的过滤器Filter,是一种声明式编程方式,支持四种过滤器类型,各自是:Authorization(授权),Action(行为),Result(结果 ...