How to use google tag manager with angular 4 correctly?

Member

by aubrey , in category: Third Party Scripts , 2 months ago

How to use google tag manager with angular 4 correctly?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 2 months ago

@aubrey 

To use Google Tag Manager with Angular 4 correctly, follow these steps:

  1. Set up your Google Tag Manager account and create a new container for your website.
  2. Install the Google Tag Manager snippet on your website by following the instructions provided in your GTM account.
  3. Install the Angular Google Tag Manager (GTM) module in your Angular 4 application by running the following command:
1
npm install angular-google-tag-manager --save


  1. Import the AngularGoogleTagManagerModule in your app.module.ts file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { AngularGoogleTagManagerModule } from 'angular-google-tag-manager';

@NgModule({
  imports: [
    ...
    AngularGoogleTagManagerModule.forRoot({
      id: 'YOUR-GTM-ID'
    })
  ],
  ...
})
export class AppModule { }


Replace 'YOUR-GTM-ID' with your actual Google Tag Manager Container ID.

  1. Add the gtm directive to your index.html file before the closing tag. The directive should be placed right after the opening tag:
1
2
3
4
5
6
7
8
<head>
  ...
</head>
<body>
  <app-root>
    <gtm></gtm>
  </app-root>
</body>


  1. Use the GtmService provided by the Angular Google Tag Manager module to push events or data layer variables to GTM. Inject the service into your components and call its methods as needed:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { GtmService } from 'angular-google-tag-manager';

@Component({
  ...
})
export class MyComponent {
  constructor(private gtmService: GtmService) { }

  trackEvent() {
    this.gtmService.pushEvent('eventCategory', 'eventAction', 'eventLabel', 'eventValue');
  }
}


  1. Make sure to test your Google Tag Manager setup in preview mode to ensure that events are being tracked correctly on your Angular 4 website.


By following these steps, you can integrate Google Tag Manager with Angular 4 and track events and data on your website effectively.