美文网首页Angular框架专题
Angular框架中的HostListener & HostBi

Angular框架中的HostListener & HostBi

作者: 听书先生 | 来源:发表于2021-11-30 23:32 被阅读0次

Host Element宿主元素,指的应用指令的元素。
创建一个更改元素背景色的指令:

import { Directive, HostListener, ElementRef, Renderer2, HostBinding, Input } from '@angular/core';

@Directive({
    selector: '[appBackgroundExe]'
})
export class BackgroundExeDirective {
    constructor(private elementRef: ElementRef, private renderer: Renderer2) {
        this.setStyle();
    }

    private setStyle(): void {
        this.renderer.setStyle(this.elementRef.nativeElement, 'background', '#000');
        this.renderer.setStyle(this.elementRef.nativeElement, 'color', '#FFF');
    }
}

<p appBackgroundExe>
  <span>测试的文本内容</span>
</p>
  • selector用于匹配元素:
element-name: 元素名匹配,如 exe-app
.class: 类名匹配,如 .intro
[attribute]: 属性名匹配,如 [target]
[attribute=value]: 属性名和属性值匹配,如 [target=_blank]
:not(sub_selector): 非(sub_selector) 匹配,如 :not(p)
selector1, selector2: selector1、selector2 匹配,如 div,p
1、HostListener

HostListener是属性装饰器,用来为宿主元素添加事件监听的。

  • HostListenerDecorator装饰器的定义:
export interface HostListenerDecorator {
  (eventName: string,args?: string[]):any;
  new (eventName: string,args?: string[]):any;
}
  • HostListenerDecorator装饰器的使用:
    HostListenerDecorator装饰器主要通过@HostListener的方式去实现宿主元素的事件创建
import { Directive, HostListener, ElementRef, Renderer2, HostBinding, Input } from '@angular/core';

@Directive({
    selector: '[appBackgroundExe]'
})
export class BackgroundExeDirective {

    @Input('appBackgroundExe')
    highLightColor!: string;

    constructor(private elementRef: ElementRef, private renderer: Renderer2) {
        this.initStyle();
    }

    @HostListener('mouseenter')
    onMouseEnter(): void {
        this.highLight(this.highLightColor);
    }

    @HostListener('mouseleave')
    onMouseLeave(): void {
        this.initStyle();
    }

    // 设置悬浮高亮的效果
    private highLight(color: string): void {
        this.renderer.setStyle(this.elementRef.nativeElement, 'background', color);
    }

    // 初始化宿主元素的样式
    private initStyle(): void {
        this.renderer.setStyle(this.elementRef.nativeElement, 'background', '#000');
        this.renderer.setStyle(this.elementRef.nativeElement, 'color', '#FFF');
    }

}

在template模板中进行使用:

<p [appBackgroundExe] = "'red'">
  <span>测试的文本内容</span>
</p>

可以看到鼠标的悬浮效果是已经添加至宿主元素中去。
在使用这个装饰器的时候,我们除了监听宿主元素,还能对其他对象进行事件的定义。比如我们可以去监听window对象。

    @HostListener('document:click',['$event'])
    onClick(e:any): void {
        // 判断是否点击了宿主元素
        if(this.elementRef.nativeElement.contains(e.target)){
            this.highLight('blue')
        }else{
            this.highLight('')
        }
    }

也可以在指令的 metadata 信息中,设定宿主元素的事件监听信息。

import { Directive } from '@angular/core';

@Directive({
    selector: 'button[counting]',
    host: {
      '(click)': 'onClick($event.target)'
    }
})
export class CountClick {
    count = 0;

    onClick(btn: HTMLElement) {
        console.log('number of clicks:', this.count++);
    }
}
HostBinding

HostBinding是属性装饰器,用来动态设置宿主元素的属性值。

  • HostBinding装饰器定义:
export interface HostBindingDecorator {
    (hostPropertyName?: string): any;
    new (hostPropertyName?: string): any;
}
  • HostBinding装饰器的使用:
import { Directive, HostListener, ElementRef, Renderer2, HostBinding, Input } from '@angular/core';

@Directive({
    selector: '[appBackgroundExe]',
    host: {
        '(click)': 'onClick($event.target)'
      }
})
export class BackgroundExeDirective {

    @Input('appBackgroundExe')
    highLightColor!: string;

    constructor(private elementRef: ElementRef, private renderer: Renderer2) {
        this.initStyle();
    }

    @HostBinding('class.pressed')
    isPressed!: boolean;

    @HostListener('mousedown')
    onMouseDown(): void {
        this.isPressed = true;
    }

    @HostListener('mouseup')
    onMouseUp(): void {
        this.isPressed = false;
    }

    // 初始化宿主元素的样式
    private initStyle(): void {
        this.renderer.setStyle(this.elementRef.nativeElement, 'background', '#000');
        this.renderer.setStyle(this.elementRef.nativeElement, 'color', '#FFF');
    }

}

  • Host Property Bindings
    可以在指令的metadata信息中去设置宿主元素的属性绑定信息。
import { Directive, HostListener } from '@angular/core';

@Directive({
    selector: '[exeButtonPress]',
    host: {
      '[class.pressed]': 'isPressed'
    }
})
export class ExeButtonPress {
    isPressed: boolean;

    @HostListener('mousedown') hasPressed() {
        this.isPressed = true;
    }
    @HostListener('mouseup') hasReleased() {
        this.isPressed = false;
    }
}

相关文章

网友评论

    本文标题:Angular框架中的HostListener & HostBi

    本文链接:https://www.haomeiwen.com/subject/teejxrtx.html