Facebook Pixel integration in Angular with multiple pixel IDs

Abhinav Akhil
5 min readJan 7, 2023

--

Facebook Pixel is a tracking tool by Facebook now Meta, which will help you to track visitors and their activities on your website/app. It also helps you to target those visitors when you advertise on Meta.

Behind the scenes, The Facebook Pixel is a snippet of JavaScript code that loads a small library of functions, you can use to track Facebook ad-driven visitor activity on your website. It relies on Facebook cookies, which enable us to match your website visitors to their respective Facebook User accounts. Once matched, we can tally their actions in the Facebook Ads Manager so you can use the data to analyze your website’s conversion flows and optimize your ad campaigns.

By default, the Pixel will track URLs visited, domains visited, and the devices your visitors use. In addition, you can use the Pixel’s library of functions to:

The pixel code looks something like this:

<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '{your-pixel-id-goes-here}');
fbq('track', 'PageView');
</script>
<noscript>
<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id={your-pixel-id-goes-here}&ev=PageView&noscript=1"/>
</noscript>
<!-- End Facebook Pixel Code -->

But you cannot add dynamic pixel IDs using this code in your Angular app.

So is there a better solution for this in the Angular app?

The answer is Yes we do, We have ngx-multi-pixel to the rescue.

ngx-multi-pixel is an angular library to simplify tracking using a Facebook Pixel. It supports multiple pixel Ids and it helps us to set dynamic pixel ids to our angular application and track events. Let me guide you step by step on how you can implement ngx-multi-pixel in your angular application.

Using ngx-multi-pixel is very simple, just follow the below steps:

  1. You can install this NPM package with npm install ngx-multi-pixel
  2. Add the library to your app’s module, usually app.module.ts. Make sure you use the forRoot() method. Within this method, add your Facebook Pixel ID.
import { PixelModule } from "ngx-multi-pixel";
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
PixelModule.forRoot({ enabled: true, pixelId: ["YOUR_PIXEL_IDS"] }),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

NOTE: By default, the library does not start tracking immediately. In most cases, this requires user consent to comply with GDPR and other privacy regulations. If you would still like to start tracking as soon as your app module loads, include the enabled: true parameter when you call forRoot().

3. Add it to your components

In any component where you would like to track certain events, you can import the PixelService import { PixelService } from 'ngx-multi-pixel'; Then you can inject the service into your component as follows:

import { PixelService } from 'ngx-multi-pixel';

export class HomeComponent {

constructor(
private pixel: PixelService
) { }

}

4. Tracking events

There are two groups of events that you can track, namely Standard events and Custom events.

Standard events are common events that Facebook has created. You can find the full list here.

The first argument is the type of event as defined by Facebook. The optional second argument can be used to pass on more information about the event. For example:-

this.pixel.track("InitiateCheckout", {
content_ids: ["ABC123", "XYZ456"], // Item SKUs
value: 100, // Value of all items
currency: "USD", // Currency of the value
});

Custom events as the name suggest help create custom events with a function called trackCustom(). The first argument is the customEventName( can be any name ) and just like with Standard events, you can add more properties. This is recommended since this enables you to create even more specific audiences within Facebook Business Manager. Which properties you add is completely up to you. Here is an example:

this.pixel.trackCustom("customEventName", {
amount: 100,
currency: "USD",
platform: "linewire"
// etc...
});

5. Enabling ngx-multi-pixel immediately.

It is still possible to initialize ngx-multi-pixel as soon as your app module loads. When adding ngx-multi-pixel to app.module.ts, add the parameter enabled: true.

imports: [
BrowserModule,
PixelModule.forRoot({ enabled: true, pixelId: ["YOUR_PIXEL_IDS"]})
],

6. Enabling ngx-multi-pixel from a component

You can also enable ngx-multi-pixel from within any of your components, like so:

import { PixelService } from 'ngx-multi-pixel';

export class HomeComponent implements OnInit{

constructor(
private pixel: PixelService
) { }

ngOnInit(): void {
this.onConsent();
}

onConsent(): void {
this.pixel.initialize();
// or
// this.pixel.initialize(['pixelId1', 'pixelId2',...]);
}

}

7. Enabling with a dynamic Pixel ID

In situations where the Pixel ID needs to be changed dynamically, this can be done using initialize() with the new Pixel ID as an optional argument.

Notes:

  • A Pixel ID still needs to be provided when importing ngx-multi-pixel in the module.
  • The previous instance should be removed with remove() before initializing a new Pixel ID.
  • This approach should not be used in combination with serverside rendering (SSR). As the module is initialized on each request, the Pixel script will default to the ID provided in the module.
import { PixelService } from 'ngx-multi-pixel';

export class HomeComponent implements OnInit{

constructor(
private pixel: PixelService
) { }

ngOnInit(): void {
this.onConsent();
}

onConsent(): void {
this.pixel.initialize(['pixelId1', 'pixelId2',...]);
}

}

8. Disabling ngx-multi-pixel

Disabling works very similar to enabling from within a component and looks like this:

import { PixelService } from 'ngx-multi-pixel';

export class HomeComponent implements OnInit{

constructor(
private pixel: PixelService
) { }

ngOnInit(): void {
this.onRevokeConsent()
}

onRevokeConsent(): void {
this.pixel.remove();
}

}

Note: ngx-multi-pixel doesn't support server-side rendering, In case if you are using SSR in your angular app, then please load this.pixel.initialize() code inside the browser not on the server.

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
import { PixelService } from 'ngx-multi-pixel';

export class HomeComponent implements OnInit {

constructor(
private pixel: PixelService,
private @Inject(PLATFORM_ID): platformId: Object,
) {
this.isBrowser = isPlatformBrowser(platformId);
}

ngOnInit(): void {
if(this.isBrowser){
this.onConsent();
}
}

onConsent(): void {
this.pixel.initialize(['pixelId1', 'pixelId2',...]);
}

}

and now the final step is to run the angular app and you can test, if the Facebook pixels are working or not by adding Facebook Pixel Helper extensions from chrome and it would look something like the following.

So you have successfully implemented Facebook Pixel in your Angular app.

Thanks for reading it through to the end. I hope the article has helped you in learning something new. Happy Coding, Thanks.

--

--

Abhinav Akhil
Abhinav Akhil

Written by Abhinav Akhil

I create software, that tell stories.

No responses yet