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

时间:2018-06-19 12:04:42

标签: angular typescript

如何在可被所有文档触发的组件内的角度2中设置事件侦听器({{range .CartList}} {{if .ID}} {{.ID}} {{.Name}} {{.Description}} {{else}} No Articles in your Cart available {{end}} {{end}} )?回调函数会在组件内部调用一个函数

类似这样的内容(用Java语言编写):

mouseup

4 个答案:

答案 0 :(得分:2)

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);
  }

}

答案 1 :(得分:0)

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

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

组件内部

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

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

要在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;
        }
    }

希望这会对您有所帮助。

相关问题