Tagging an Angular 2+ site

Foreword

Before beginning implementation of our tagging solution, please make sure you have selected the desired plugins from within the Tag Composer interface.

Principle

The proposed solution consists of adding a service and a directive depending on your tagging needs. The code, provided as an example, allows you to measure pages and clicks. However, it is possible to add any type of Tracker features by applying the same principles as those described.

Tagging

If needed, it is possible to use a directive for the integration of a tag into the HTML code of a component, or to use a service for integration into a component class.

Integration

The integration examples rely on the following project tree structure:

The “quickstart” project includes the code:

of a tagging service “src/app/lib/atinternet/_services/tag.service.js”

of a tagging directive “src/app/lib/atinternet/_directives/tag.directive.ts”

of the SmartTag JS “src/app/lib/atinternet/_vendors/smarttag.js”

Tagging service

The tagging service is useful for integrating a tag into the TypeScript code of a component.

The “clickSend” function takes the click event “$event“ as a parameter. This event will serve as an automatic click management mechanism for the Tracker, useful for the resolution of “cancelled” clicks.

Tagging directive

The tagging directive is useful for tagging an HTML element of a component.

Directive example

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

import{Directive,ElementRef,Input}from'@angular/core';

import{TagService}from"../_services/tag.service"

@Directive({

selector:'[atTag]'

})

exportclassTagDirective{

constructor(private el:ElementRef,private tagService:TagService){}

@Input()clickData:any;

@Input()pageData:any;

ngAfterViewInit(){

if(this.pageData&&typeofthis.pageData==='object'){

this.tagService.pageSend(this.pageData);

}

if(this.clickData&&typeofthis.clickData==='object'){

this.clickData.elem=this.el.nativeElement;

this.tagService.clickListener(this.clickData);

}

}

}

Here, the directive “TagDirective” (selector atTag) relies on the tagging service “TagService” to conduct click measurement with listener as well as page measurement.