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>