首页 > 代码库 > [Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2
[Angular Directive] Build a Directive that Tracks User Events in a Service in Angular 2
A @Directive
is used to add behavior to elements and components in your application. This makes @Directive
s 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。