zoukankan      html  css  js  c++  java
  • [Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2

    @Directive is used to add behavior to elements and components in your application. This makes @Directives ideal for behaviors such as "tracking" which don't belong in a Component, but do belong as a behavior in your application.

    import {Directive, HostListener, Input} from '@angular/core';
    import {TrackingService} from "../services/tracking.service";
    
    @Directive({
      selector: '[track]'
    })
    export class TrackDirective {
    
      @Input() track;
    
      constructor(private trackingService: TrackingService) { }
    
      @HostListener('click', ['$event']) onClick(event) {
        this.trackingService.tracking(
          event,
          this.track
        )
      }
    }
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class TrackingService {
    
      logs = [];
      constructor() { }
    
      tracking(event, log) {
        this.logs.push({
          event,
          log
        });
    
        console.log(this.logs)
      }
    }
    <button [track]="'one is clicked'">One</button>
    <button [track]="'two is clicked'">Two</button>
    <button [track]="'three is clicked'">Three</button>
  • 相关阅读:
    DAG:区块链行业下一个引爆点?
    php7的新特性
    Linux中的冷热页机制概述
    撰写后台需求文档需要注意的那些事儿
    poj 1201 Intervals
    poj 1364
    poj Candies
    hdu 1429
    poj A Round Peg in a Ground Hole
    poj 1113Wall
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6211995.html
Copyright © 2011-2022 走看看