码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2

时间:2016-12-22 19:26:49      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:one   for   listen   event   ack   exp   elements   bsp   services   

@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>

 

[Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2

标签:one   for   listen   event   ack   exp   elements   bsp   services   

原文地址:http://www.cnblogs.com/Answer1215/p/6211995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!