原文

  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的更多相关文章

  1. [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 ...

  2. Angular4 @HostBinding @HostListener

    host属性 @Component({ selector: 'jhi-project', templateUrl: './project.html', styleUrls: [], host: { ' ...

  3. [Angular 2] Directive intro and exportAs

    First, What is directive, what is the difference between component and directive. For my understandi ...

  4. Angular 4+ 修仙之路

    Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...

  5. [Angular] Test Directive

    directive: import { Directive, HostListener, HostBinding, ElementRef } from '@angular/core'; @Direct ...

  6. [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 ...

  7. [Angular] Using directive to create a simple Credit card validator

    We will use 'HostListener' and 'HostBinding' to accomplish the task. The HTML: <label> Credit ...

  8. [转]angular 监听窗口滚动

    本文转自:https://blog.csdn.net/ittvibe/article/details/80060801 转自:http://brianflove.com/2016/10/10/angu ...

  9. Angular @HostBinding()和@HostListener()用法

    @HostBinding()和@HostListener()在自定义指令时非常有用.@HostBinding()可以为指令的宿主元素添加类.样式.属性等,而@HostListener()可以监听宿主元 ...

随机推荐

  1. C# WPF开源控件库MaterialDesign介绍

    介绍 1.由于前端时间萌发开发一个基础架构得WPF框架得想法, 然后考虑到一些界面层元素统一, 然后就无意间在GitHub上发现一个开源WPF UI, 于是下载下来了感觉不错. 官网地址:http:/ ...

  2. 关于bat的变量赋值和解析机制

    以下的演示涉及几个知识点: 1. 怎样把命令输出内容保存到变量中? 2. 多次改变变量值,为什么在for或是if的()中的无效,怎样变通? 3. bat的function实现? 见代码,和代码凝视 : ...

  3. 【Material Design视觉设计语言】应用样式设计

    作者:郭孝星 微博:郭孝星的新浪微博 邮箱:allenwells@163.com 博客:http://blog.csdn.net/allenwells Github:https://github.co ...

  4. Oracle 11gR2光钎链路切换crs服务发生crash

    Oracle 11gR2光钎链路切换crs服务发生crash 背景: 我们将Oracle 11gR2(11.2.0.4)在RedHat EnterPrise 5.8上通过RDAC完毕的多路径链路冗余. ...

  5. 自己定义控件的onMeasure方法具体解释

    在我们自己定义控件的时候可能你会用到onMeasure方法,以下就具体的给大家介绍一下这种方法: @Override protected void onMeasure(int widthMeasure ...

  6. APACHE2.4 指定目录中的字符编码

    APACHE2.4 指定目录中的字符编码 xampp 的 apache2.4 默认字符编码是西文,中文字符显示乱码,在 httpd.conf 没有 AddDefaultCharset utf-8 这样 ...

  7. Django路由分配以及模版渲染

    路由上: 在网络上区分不同的电脑通过IP.端口和网卡的MAC地址等,在web框架中怎么区分不同的请求呢,就是通过 ‘url(路由)’ ,url 学名叫做全球统一资源定位符,其实就是一个网址 一个url ...

  8. 微信小程序仿微信运动步数排行-交互

    效果图如下: 图片.png wxml: <view class="item-box"> <view class="items"> < ...

  9. 洛谷 P1032 字符变换

    洛谷 P1032 字符变换 题目描述 已知有两个字串 A,B 及一组字串变换的规则(至多 6 个规则): A1​ -> B1​ A2​ -> B2​ 规则的含义为:在 A 中的子串 A1​ ...

  10. 4.auto详解

    #include <iostream> using namespace std; template <calss T1,class T2> auto add(T1 t1, T2 ...