繁体   English   中英

组件内文档上的Angular 2事件监听器

[英]Angular 2 Event listener on document inside a component

如何在可以由所有文档触发的组件内部的angular 2中设置事件侦听器( mouseup )? 回调函数将在组件内部调用一个函数

这样的东西(用JavaScript):

document.addEventListerner('mouseup', function(){
    if( condition ){
       // code ..
    }
});

https://stackblitz.com/edit/angular-host-listener-mouseup?file=src%2Fapp%2Fapp.component.ts

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  @HostListener('window:mouseup', ['$event'])
  onMouseUp(event) {
    console.log(event);
  }

}

添加HostListener以在文档对象上注册事件

import {HostListener, KeyboardEvent} from '@angular/core';

在组件内部

  @HostListener('mouseup', ['$event'])
  mouseUp(ev:KeyboardEvent) { 
    console.log(ev);
  } 

使用@HostListener装饰器在组件中注册mouseup事件

https://stackblitz.com/edit/angular-2iktzs

@HostListener('window:mouseup', ['$event'])
onMouseUp(event) {
  console.log("mouse clicked and released");
}

要在angular中使用mouse up事件,请创建指令并使用主机侦听器可以触发事件。 在app.module中声明指令后,将选择器名称与html属性/标签一起使用。

import { Directive, Attribute, ElementRef, HostListener, Renderer } from '@angular/core';
    // Directive to for mouse up event
    @Directive({
        selector: '[mouseup]'
    })

    export class MouseUpDirective {

        private el: any;

        constructor( el: ElementRef ) {
            this.el = el.nativeElement;
        }

        @HostListener('mouseup')
        onMouseUp() {
            this.highlight('yellow');
        }

        private highlight(color: string) {
            this.el.style.backgroundColor = color;
        }
    }

希望这会帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM