Code Monkey home page Code Monkey logo

angular-google-tag-manager's Introduction

Angular Google Tag Manager Service

A service library for integrate google tag manager in your angular project This library was generated with Angular CLI For more info see this how to install google tag manager article

Getting Started

After installing it you need to provide your GTM id in app.module.ts

    providers: [
        ...
        {provide: 'googleTagManagerId',  useValue: YOUR_GTM_ID}
    ],

Or use the module's forRoot method

import { GoogleTagManagerModule } from 'angular-google-tag-manager';

imports: [
    ...
    GoogleTagManagerModule.forRoot({
      id: YOUR_GTM_ID,
    })
]

Or use the APP_INITIALIZER

import { GoogleTagManagerConfiguration } from 'angular-google-tag-manager-config.service';

imports: [
    ...
    GoogleTagManagerModule.forRoot()
]

providers: [
    {
      ...
      provide: APP_INITIALIZER,
      useFactory: configInitializer,
      deps: [
        HttpBackend,
        GoogleTagManagerConfiguration,
      ],
      multi: true,
    },
  ],

set the config in the method assigned to useFactory

googleTagManagerConfiguration.set(googleTagManagerConfiguration);

inject the gtmService in your controller

constructor(
        ...
        private gtmService: GoogleTagManagerService,
    ) { }

then you can start pushing events on your gtm

 this.router.events.forEach(item => {
            if (item instanceof NavigationEnd) {
                const gtmTag = {
                    event: 'page',
                    pageName: item.url
                };

                this.gtmService.pushTag(gtmTag);
            }
        });

if you want to recive tags without pushing events simply call the function to enable it

    this.gtmService.addGtmToDom();

Installing

In your Angular project run

npm i --save  angular-google-tag-manager

Custom configuration and GTM environments

You can pass gtm_preview and gtm_auth optional variables to your GTM by providing them in app.module.ts

    providers: [
        ...
        {provide: 'googleTagManagerId',  useValue: YOUR_GTM_ID},
        {provide: 'googleTagManagerAuth',  useValue: YOUR_GTM_AUTH},
        {provide: 'googleTagManagerPreview',  useValue: YOUR_GTM_ENV},
        {provide: 'googleTagManagerResourcePath',  useValue: YOUR_GTM_RESOURCE_PATH},
        {provide: 'googleTagManagerCSPNonce',  useValue: YOUR_CSP_NONCE},
        {provide: 'googleTagManagerMode', useValue: "silent" | "noisy"}
    ],

Or using forRoot

import { GoogleTagManagerModule } from 'angular-google-tag-manager';

imports: [
    ...
    GoogleTagManagerModule.forRoot({
      id: YOUR_GTM_ID,
      gtm_auth: YOUR_GTM_AUTH,
      gtm_preview: YOUR_GTM_ENV
    })
]

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License

Acknowledgments

angular-google-tag-manager's People

Contributors

alvarocjunq avatar bursauxa avatar dependabot[bot] avatar gravllift avatar hireception avatar limitofzero avatar liollury avatar mathieuzimmo avatar mzuccaroli avatar nils-thomann avatar nilsthomann avatar perrymartijena avatar stephanegraziano avatar yberion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

angular-google-tag-manager's Issues

Getting Unresolved depenedencies when updating angulat to version 11.

While updating from angular 8 to angular 11. i am getting the following errors.

91 error code ERESOLVE 92 error ERESOLVE unable to resolve dependency tree 93 error 94 error While resolving: [email protected] 94 error Found: @angular/[email protected] 94 error node_modules/@angular/common 94 error @angular/common@"^11.2.14" from the root project 94 error 94 error Could not resolve dependency: 94 error peer @angular/common@"^12.0.3" from [email protected] 94 error node_modules/angular-google-tag-manager 94 error angular-google-tag-manager@"^1.4.2" from the root project

is there an specific version compatible with angular 11?

Question. Publishing events to GTM

Hello and thanks for this library!

My question is about publishing events to GTM.
I inserted pushing tags to dataLayer wherever I need and it works perfectly when I start debugging session from GTM. Events go there and I see all of data published to dataLayer array.

But when I disconnect debugger or don't start it at all the data from dataLayer is not publishing to GTM at all. I don't see any network calls :(

I use version 1.1.4.

Thanks in advance.

Angular 10 compatibilities and peer references

Please update the references to support the latest version of angular,
also perhaps move the angular etc dependencies into peerDependencies as all of them are pretty standard for a typical angular app.

Thanks

"export 'ɵɵdefineInjectable' was not found in '@angular/core'

Hi
I am trying to implement GTM in angular application.

"@angular/common": "^6.1.0",
"@angular/compiler": "^6.1.0",
"@angular/core": "^6.1.0",

Above is my configuration. I have installed GTM from NPM and when I am building the solution I am coming across below warning

WARNING in ./src/node_modules/angular-google-tag-manager/fesm2015/angular-google-tag-manager.js
166:51-69 "export 'ɵɵdefineInjectable' was not found in '@angular/core'

When I am trying to load the application i am getting below error

angular-google-tag-manager.js:166 Uncaught TypeError: Object(...) is not a function
at Object../src/node_modules/angular-google-tag-manager/fesm2015/angular-google-tag-manager.js (angular-google-tag-manager.js:166)
at webpack_require (bootstrap:81)
at Object../src/app/app.component.ts (main.js:2859)
at webpack_require (bootstrap:81)
at Object../src/app/app.module.ts (app.material.ts:87)
at webpack_require (bootstrap:81)
at Object../src/main.ts (main.ts:1)
at webpack_require (bootstrap:81)
at Object.0 (main.ts:14)
at webpack_require (bootstrap:81)

GoogleTagManagerService static injection error

I believe this has been recently updated and this has resulted in some issues in compilation of old Angular Apps like version 8.
The service now needs to be imported in the provider array of the root app module.
Screenshot from 2020-09-21 19-48-59

400 Error when using in live env

I'm using the code below to dynamically add the ID based on a URL. Here is an example of it in use:
https://xilo-dev-forms.herokuapp.com/client-app/form/page/start?companyId=357974&gtagId=GTM-WBJL4SD&agent=ssachdev20%[email protected]&formId=6

main-es2015.18f7e95ce1f60d738dac.js:1 GET https://www.googletagmanager.com/gtm.js?id= net::ERR_ABORTED 400
addGtmToDom @ main-es2015.18f7e95ce1f60d738dac.js:1
pushTag @ main-es2015.18f7e95ce1f60d738dac.js:1

www.googletagmanager.com/ns.html?id=:1 Failed to load resource: the server responded with a status of 400 ()

locally all works well and the tag fires. In live environments like staging and develop it fails to append the ID. Youll see below Im dynamically adding the ID but if you look at the console it prints just fine which I assume means it should be passing the the provider correctly.

Any idea what Im doing wrong?

import { ErrorHandler, NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MomentModule} from "angular2-moment";
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
import { FormMethodService } from './services/form-method.service';
import { UnknownComponent } from './unknown.component';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgxLoadingModule } from 'ngx-loading';
import { FormsModule } from '@angular/forms';

let gtmId = '';

if (window.location.href.toString().includes('gtagId')) {
  const vars = {};
  const parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    return vars[key] = value;
  });
  gtmId = vars['gtagId'];
  console.log(gtmId);
}

@NgModule({
  declarations: [
      AppComponent,
  ],
  imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule,
],
  providers: [
    {provide: 'googleTagManagerId', useValue: gtmId}  
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

peer dependencies error after published 1.4.3 version

Hi,

In my project with Angular 8 (sorry about that), if you delete node-modules and run "npm install' I got

npm WARN [email protected] requires a peer of @angular/common@^12.0.3 but none is installed. You must install peer dependencies yourself.

Ok, just a WARN.. In my packahe.json I have:

"dependencies": {
...
"angular-google-tag-manager": "^1.4.1",
...
}

After install, doesn't appears "google-tag-manager" folder inside node-modules and when I run my project or execute testes, I got:

Cannot find module 'angular-google-tag-manager' from 'src/app/[project file].ts'

I solved with

"dependencies": {
...
"angular-google-tag-manager": "=1.4.1",
...
}

But I don't know why I got that error. That didn't happen with 1.4.2 version published.

DOC issue: which controller should i inject the service into?

I want to do the equivalent of adding the tag

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

into the head/body of every page of an app. (but use an npm /ng lib)
does this pkg do that?

I guess i have to add it to the router?

Get the GTM ID from external (lazyload angular-google-tag-manager module)

Hi !

I'm working on projects who need to setup different GTM ID in each environnement.
The variable comme from an API call and cannot be setup in the env files.

I have try to do, something like that:

`import {map} from 'rxjs/operators';
import {API_PUBLIC} from '../../../environments/environment';
import {HttpClient} from '@angular/common/http';
import {GoogleTagManagerConfig} from 'angular-google-tag-manager';

export function googleTagManagerConfigFactory(http: HttpClient, gtConf: GoogleTagManagerConfig) {
return () => http.get<{ gtmTag: string }>(API_PUBLIC + '/config').pipe(
map(response => {
if (gtConf) {
gtConf.id = response.gtmTag;
return response.gtmTag;
}
})
).toPromise();
}`

providers: [ {provide: GoogleTagManagerConf, useFactory: googleTagManagerConfigFactory} ]

But i'm facing with this error => ERROR in ./src/app/app.module.ts 123:31-51
"export 'GoogleTagManagerConf' was not found in 'angular-google-tag-manager'

Do you have a solution to lazy load the angularTagManagerModule ?

Using library

Hello
Where i can use this.gtmService.addGtmToDom();
and have i declare gtmService?
I'm using Angular 8,
Thanks

'ɵɵinject' / 'ɵɵdefineInjectable' not found in '@angular/core'

Hi!
I can' use this library on my Angular Project because I receive these warnings, when I make ng serve:

WARNING in ./node_modules/angular-google-tag-manager/fesm5/angular-google-tag-manager.js "export 'ɵɵinject' was not found in '@angular/core'

WARNING in ./node_modules/angular-google-tag-manager/fesm5/angular-google-tag-manager.js "export 'ɵɵdefineInjectable' was not found in '@angular/core'

It may be that I did something wrong, but I can't understand why.

This is my tsconfig.json :

{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}

And then, my package.json :

{
"name": "test",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^7.0.0",
"@angular/common": "^7.0.0",
"@angular/compiler": "^7.0.0",
"@angular/core": "^7.0.0",
"@angular/forms": "^7.0.0",
"@angular/http": "^7.0.0",
"@angular/platform-browser": "^7.0.0",
"@angular/platform-browser-dynamic": "^7.0.0",
"@angular/router": "^7.0.0",
"@ng-toolkit/universal": "^7.1.2",
"@ngx-translate/core": "^11.0.1",
"@ngx-translate/http-loader": "^4.0.0",
"angular-google-tag-manager": "^1.1.1",
"chart.js": "^2.8.0",
"classlist.js": "^1.1.20150312",
"core-js": "^2.5.4",
"moment": "^2.24.0",
"ng2-charts": "^2.2.0",
"ng2-nouislider": "^1.8.2",
"ng2-pdf-viewer": "^6.0.1",
"ngx-useful-swiper": "^8.0.1",
"nouislider": "^13.1.5",
"rxjs": "^6.0.0",
"swiper": "^4.5.0",
"web-animations-js": "^2.3.2",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.6.8",
"@angular/cli": "^6.0.8",
"@angular/compiler-cli": "^7.0.0",
"@angular/language-service": "^7.0.0",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"@types/swiper": "^4.4.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1",
"typescript": "~3.1.1"
}
}

angular 6 its throws error

eedefineInjectable, eeInject is not known function.

instead of defineInjectable, inject it will work in angular 6.

can have any version of this package which using defineInjectable,inject

Ivy compatibility

Error message displayed in the console :

This likely means that the library (angular-google-tag-manager/lib/angular-google-tag-manager.module) which declares GoogleTagManagerModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

Infinite tag triggering given a single dataLayer push

Hi guys, thanks for the library. Appreciated.

I have this snippet that I am sure is being called only once:

sendAnalytics(text: string) { console.log("calling GTM push") const gtmTag = { event: 'user_search', text: text, } this.gtmService.pushTag(gtmTag) }

Being 'text' a custom data layer variable previously defined in GTM.

Then, I have created a custom HTML tag:

<script> console.log("CUSTOM HTML text value: " + {{text}}) gtag('event', 'user_search', {'event_label': {{text}} }); fbq('track', 'user_search'); </script>

With a custom trigger for events containing 'user_search'.

Then, I can see the custom HTML code is being called thousand times before crashing and this.gtmService.pushTag is only called once.

I believe is a quite simple config and I assume it should be only called once.

Could you help?

Thanks.

Multiple installations of Google Tag Manager detected

Hey @mzuccaroli , Thanks for the GTM lib it helps a lot,
btw I'm facing the issue I am using addGtmToDom in one component to get (Google Linker from GTM)
and pushing an Event on another component
but it injects multiple GTM scripts in HTML when I visit any of the pages again
Am I doing something wrong?
PS: I' don't want to inject GTM on all Pages (so not using outside router-outlet)

multipleGTM

Angular Universal support, issue browser javascript variables

In universal, on node.js back-end we don't have document and window variables, they are undefined. This make below error on universal.

ERROR ReferenceError: document is not defined
    at Object.documentRef (`Path`\main.js:107335:17)
    at GoogleTagManagerService.addGtmToDom (`Path`\main.js:107373:41)
    at GoogleTagManagerService.pushTag (`Path`\main.js:107392:18)
    at SafeSubscriber._next (`Path`\main.js:81712:29)
    at SafeSubscriber.__tryOrUnsub (`Path`\main.js:53361:16)
    at SafeSubscriber.next (`Path`\main.js:53300:22)
    at Subscriber._next (`Path`\main.js:53250:26)
    at Subscriber.next (`Path`\main.js:53227:18)
    at Subject.next (`Path`\main.js:88841:25)
    at SafeSubscriber._next (`Path`\main.js:182123:18)

It can be fixed by setting those variables if they are undefined on below lines
https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/projects/angular-google-tag-manager/src/lib/angular-google-tag-manager.service.ts#L12
https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/projects/angular-google-tag-manager/src/lib/angular-google-tag-manager.service.ts#L15

Versão 1.1.1 pra frente com problema no build

Olá assim que vocês publicaram uma nova versão no npm o projeto que estou trabalhando tem apresentado esse problema na hora do build.

Warning: Can't resolve all parameters for TagService in /app/src/app/data/tag/tag.service.ts: (?, [object Object]). This will become an error in Angular v6.x
Warning: Can't resolve all parameters for TagService in /app/src/app/data/tag/tag.service.ts: (?, [object Object]). This will become an error in Angular v6.x
ERROR in src/app/data/tag/tag.service.ts:4:41 - error TS2307: Cannot find module 'angular-google-tag-manager'.
4 import { GoogleTagManagerService } from 'angular-google-tag-manager';

Estou usando a versão no @angular/cli@^8.3.25 e @angular/core@~8.2.14

image

peerDependencies warning

Could you please update library peer dependencies to support different angular version, currently in jas angular v7.2.2

Thanks for the awesome library!

Library throws error when building the code

Package Dependencies:

"dependencies": {
"@angular/animations": "~9.0.3",
"@angular/cdk": "^9.2.4",
"@angular/common": "~9.0.3",
"@angular/compiler": "~9.0.3",
"@angular/core": "~9.0.3",
"@angular/forms": "~9.0.3",
"@angular/material": "^9.2.4",
"@angular/platform-browser": "~9.0.3",
"@angular/platform-browser-dynamic": "~9.0.3",
"@angular/router": "~9.0.3",
"@azure/msal-angular": "^2.0.2",
"@azure/msal-browser": "^2.15.0",
"@ngx-formly/core": "^5.10.22",
"@ngx-formly/material": "^5.10.22",
"angular-google-tag-manager": "^1.4.4",
"angular-mydatepicker": "^0.11.4",
"angular-ng-stepper": "^1.0.6",
"bn-ng-idle": "^1.0.1",
"chart.js": "^2.9.3",
"chartjs-plugin-datalabels": "^1.0.0",
"core-js": "^3.16.1",
"karma-sonarqube-unit-reporter": "0.0.23",
"net": "^1.0.2",
"ng2-charts": "^2.2.3",
"rxjs": "^6.5.5",
"rxjs-compat": "^6.6.7",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.4",
"@angular/cli": "~9.0.4",
"@angular/compiler-cli": "~9.0.3",
"@angular/language-service": "~9.0.3",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"prettier": "^2.3.0",
"protractor": "~5.4.3",
"stickyfilljs": "^2.1.0",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "~3.7.5",
"webpack-bundle-analyzer": "^4.4.2"
}

Error :
image
image
image

ɵɵdefineInjectable undefined

Hi,

trying to update angular-google-tag-manager, from 0.0.1 to 1.4.2, i get this error

TypeError: undefined is not a function (near '...r["\u0275\u0275defineInjectable"]...')

Coming from line 89 in angular-google-tag-manager.js

If someone ever ended up having this error, i could use a hand :)

Support Angular 13

Since our project upgrade to angular 13. Jest test will report Unexpected value 'GoogleTagManagerModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

"export 'ɵɵinject' was not found in '@angular/core'

Hi there awesome package, using it in Angular 7 (@angular/core : 7.2.7) gives this warning
WARNING in ./node_modules/angular-google-tag-manager/fesm5/angular-google-tag-manager.js 141:65-83
"export 'ɵɵdefineInjectable' was not found in '@angular/core'

during build and app fails to load due to same error? Anything I can check ?

Cross-site Cookie Issue

Getting this issue for Google cookies:

Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute

Support for Angular 12

angular-google-tag-manager should allow peer dependency of Angular 12. When doing npm install, the following errors appear:

npm WARN [email protected] requires a peer of @angular/common@^11.0.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@^11.0.7 but none is installed. You must install peer dependencies yourself.

However, as far as I can tell, everything seems to be working fine with on Angular 12, so I think the peer dependencies of angular-google-tag-manager should be updated to also accept Angular 12

[feature request] make noscript tag optional (as it makes only sense with angular universal)

As the <noscript> tag will probably never be added to the app if the browser does not support javascript in the first place, it might be a good idea to make it configurable if it should add it or not.

That way, if you need it you could at least add the <noscript> tag to your index.html hardcoded and not end up with a duplicate in your DOM.

It does make sense for Angular Universal though, as that would render it into the DOM before sending it to the Browser, though.

Angular Prerender document not defined resolved

I´d just nedded to generate an website, using the prerender approach, and when I putted this library on it, it stopped compiling the prerendered version. It´s a know issue in server side rendering, because window and document, are browser side objects.

So I´d modified the GoogleTagManager service a little, and I´m posting here for the creators opinion, I´d never sent any pull request in any git projects, so, If it´s the case, I´ll be glad to do it.

Below is the changes:

windowRef(): any {
     return (isPlatformBrowser(this.platform)) ? window : undefined;
 }

 documentRef(): any {
     return (isPlatformBrowser(this.platform)) ? document : undefined;
     }

 constructor(
     @Inject(PLATFORM_ID) private platform: Object,
     @Inject('googleTagManagerId') public googleTagManagerId: string,
     @Optional() @Inject('googleTagManagerAuth') public googleTagManagerAuth: string,
     @Optional() @Inject('googleTagManagerPreview') public googleTagManagerPreview: string
 ) {
     this.gtmId = googleTagManagerId;
     this.gtmAuth = googleTagManagerAuth;
     this.gtmPreview = googleTagManagerPreview;
 }

 public getDataLayer() {
   if (isPlatformBrowser(this.platform)) {
     const window = this.windowRef();
     window['dataLayer'] = window['dataLayer'] || [];
     return window['dataLayer'];
   }
   return;
 }

 public addGtmToDom() {
   if (isPlatformBrowser(this.platform)) {
     if (this.isLoaded) {
         return;
     }
     const doc = this.documentRef();
     this.pushOnDataLayer({
         'gtm.start': new Date().getTime(),
         event: 'gtm.js'
     });

     const gtmScript = doc.createElement('script');
     gtmScript.id = 'GTMscript';
     gtmScript.async = true;
     gtmScript.src = this.applyGtmQueryParams(
         '//www.googletagmanager.com/gtm.js'
     );
     doc.head.insertBefore(gtmScript, doc.head.firstChild);

     const ifrm = doc.createElement('iframe');
     ifrm.setAttribute(
         'src',
         this.applyGtmQueryParams('//www.googletagmanager.com/ns.html')
     );
     ifrm.style.width = '0';
     ifrm.style.height = '0';
     ifrm.style.display = 'none';
     ifrm.style.visibility = 'hidden';

     const noscript = doc.createElement('noscript');
     noscript.id = 'GTMiframe';
     noscript.appendChild(ifrm);

     doc.body.insertBefore(noscript, doc.body.firstChild);
     this.isLoaded = true;
   }
 }

 public pushTag(item: object) {
   if (isPlatformBrowser(this.platform)) {
     if (!this.isLoaded) {
         this.addGtmToDom();
     }
     this.pushOnDataLayer(item);
   }
   return;
 }

Two errors with angular 10 strict mode

Hi
I got this errors with latest update:

ERROR in node_modules/angular-google-tag-manager/lib/google-tag-manager-config.d.ts:3:5 - error TS2411: Property 'gtm_auth' of type 'string | undefined' is not assignable to string index type 'string'.

gtm_auth?: string;
~~~~~~~~

node_modules/angular-google-tag-manager/lib/google-tag-manager-config.d.ts:4:5 - error TS2411: Property 'gtm_preview' of type 'string | undefined' is not assignable to string index type 'string'.

gtm_preview?: string;

"angular-google-tag-manager": "^1.2.1"
"@angular/core": "^10.1.5",

Google Tag Manager Issue with FreshChat Widget

Hi, I am using GTM to inject FreshChat widget into our application.

I have followed the tutorial of integrating the GTM but the FreshChat is not getting triggered. The FreshChat Script is getting injected but not getting triggered.

Please see the below screenshot of the injected script.
image

I am using a similar GTM library in my other application(NuxtJs) to inject the same FreshChart widget and it is working fine there. So I ruled out that there might be some issue with my GTM setup.

Please see the below screenshot of the NuxtJs FreshChart script and Initialized widget elements
image

I haven't tried directly adding GTM to the HTML body. I want to leverage the services provided by this plugin. Let me know if I have to initialize something to trigger the FreshChat script.

Thank you

Error

"Uncaught ReferenceError: universal_variable is not defined" when call addGtmToDom

Need to Inject the service or get error: NullInjectorError: No provider for GoogleTagManagerService

I installed this today on my Angular 8 project.

I was following both the blog post
and also the readme on npm and the demo project repo.

I kept getting this error when loading the app. What resolved it was to add the GoogleTagManagerService as a provider.

This is not shown in any of the user guides - although it does add some other keys to the providers list.
In AppModule, I have

providers: [
    //...
    GoogleTagManagerService,
    {provide: 'googleTagManagerId',  useValue: 'GTM-WXRQXV6'},
  ]

I am not sure if this is due to angular, or something I am doing in my app?

I think this could be resolved by updating the readme and blog by adding the GoogleTagManagerService name to the list of providers. But then I am surprised it has not been reported by others.

GTM page view trigger

If I have setup page view trigger from GTM like image below. Then do I need to push it explicitly from my code too like
this.router.events.forEach(item => {
if (item instanceof NavigationEnd) {
const gtmTag = {
event: 'page',
pageName: item.url
};
this.gtmService.pushTag(gtmTag);
}
});
image

Support for Angular 11

angular-google-tag-manager should allow peer dependency of Angular 11. When doing npm install, the following errors appear:

npm WARN [email protected] requires a peer of @angular/common@^10.1.2 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@^10.1.2 but none is installed. You must install peer dependencies yourself.

However, everything works fine with on Angular 11, so I think the peer dependencies of angular-google-tag-manager should be updated to also accept Angular 11

Silently Fail if GTM ID is not provided. For unit tests via karma/jasmine

Is it possible to add an option to silently fail when a gtmid is not provided? We have a global log service that is using the GoogleTagManagerService to push tags and every component that uses the global logging service and has a unit test requires us to provide the googleTagManagerId.

providers: [{ provide: "googleTagManagerId", useValue: "test" }],

Add a enable property to add script tag

Hi,
Thank you for this lib! It would be great to add the script tag only if the user accepted the cookies, or if we are rendering app with Scully (for example) thanks to an Observable property (ie: enabled).

Angular 7 tracking user routing

Hello,
I have problem with tracking what page user looks at. When im hit enter, i got in Google analitics /account/login, when i enter app i still have /account/login as active website (also when im change other components still nothing change).

How my app looks:
Root ---> Account (here i have register and login form)
---> App (here i have 95% of app)

What i do:
I added package like in Your tutorial on itnext.io (but older version, im using angu 7 so 1.01 was fine). I added this snippet:

 this.router.events.forEach(item => {
            if (item instanceof NavigationEnd) {
                const gtmTag = {
                    event: 'page',
                    pageName: item.url
                };

                this.gtmService.pushTag(gtmTag);
            }
        });

I also tried to use addGtmToDom() ant upper snippet in othere componetns but didn't work.
Im missing something? its strange becouse it should work.
Where add this snippet? to router directly?

No Iframe in body tag?

The iFrame is not popping up in the body tags? Am i doing something wrong? I did follow the article linked in the NPM.

App.module.ts

`@NgModule({
declarations: [AppComponent, ParallaxDirective, DropzoneDirective, DocPipe],
imports: [
HomeModule,
HttpClientModule,
NavsModule,
AppRoutingModule,
DeferLoadModule,
AgmSnazzyInfoWindowModule,
BrowserModule,
ToastrModule.forRoot(),
AngularFireAuthModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule,
AngularFireStorageModule,
BrowserAnimationsModule,
Ng2ImgMaxModule,
ImageCropperModule,

],
providers: [
CaseService,
GeoService,
GeocodeService,
GoogleMapsAPIWrapper,
AuthService,
GoogleAnalyticsServiceService,
FilterService,
{ provide: "googleTagManagerId", useValue: "MY ID!!!" },
],
bootstrap: [AppComponent],
})

app.component.ts `

` ngAfterViewInit() {
this.setVideo();
this.gtmService.addGtmToDom();
}

constructor(
private router: Router,
private gtmService: GoogleTagManagerService
) {

this.router.events.forEach(item => {
  if (item instanceof NavigationEnd) {
    const gtmTag = {
      event: 'page',
      pageName: item.url
    }
    this.gtmService.pushTag(gtmTag)
  }
})

}`

Multiple installations of Google Tag Manager detected

my configuration:

in app.module.ts:

import { GoogleTagManagerModule } from 'angular-google-tag-manager';
imports: [
    ...
    GoogleTagManagerModule.forRoot({
      id: environment.gtm.id,
      gtm_auth: environment.gtm.gtm_auth,
      gtm_preview: environment.gtm.gtm_preview,
    })
]

in app.component.ts:

constructor(
        ...
        private gtmService: GoogleTagManagerService,
    ) { }
 this.router.events.forEach(item => {
            if (item instanceof NavigationEnd) {
                const gtmTag = {
                    event: 'atm.pageview',
                    pageHost: 'hostname',
                    pagePath: item.url,
                    pageTitle: 'title',
                };
                this.gtmService.pushTag(gtmTag);
            }
        });

Result:

image

in html:
image

my app:
Angular version: 10.2.4
Angular material: 10.2.7
angular-google-tag-manager: 1.3.0

-I have tried as import and as provider
-I tried only with id

I have the same error

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.