zoukankan      html  css  js  c++  java
  • [Angular Directive] 3. Handle Events with Angular 2 Directives

    @Directive can also listen to events on their host element using @HostListener. This allows you to add behaviors that react to user input and update or modify properties on the element without having to create a custom component.

    import {Directive, HostListener, HostBinding, Input} from '@angular/core';
    
    @Directive({
      selector: '[clickable]'
    })
    export class ClickableDirective {
      @Input('clickable') text;
      @HostBinding() get innerText() {
        if(this.text) {
          return this.text;
        }
      }
      @HostListener('click', ['$event']) onClick(event) {
        console.log(event); //MouseEvent
        this.text = event.clientX;
      }
    }

    We can add HostListener on the host element, and get '$event' pass to our handler function 'onClick'. Inside the function we are able to change the innerText of the directive.

  • 相关阅读:
    学习《MYSQL》课程,日期2017.4.25-2017.4.30
    Netty学习笔记
    WebSocket学习
    Class 泛型
    SAX解析与DOM解析
    HashMap和HashTable的区别
    SQL语句整理
    观察者模式学习
    状态模式学习
    策略模式学习
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6206207.html
Copyright © 2011-2022 走看看