James Lewis
James Lewis

Reputation: 303

Using Facebook advertising tracking pixels in Angular 2 / 4

I'm trying to work out how I use the Facebook tracking pixel with my angular project.

I have added the base pixel into my index.html

but I want to fire an event from the javascript, how do I fire this

fbq('track', 'CompleteRegistration');

Angular will not compile when I have this in my code as it can't find fbq

Upvotes: 7

Views: 6832

Answers (3)

Himanshu Patni
Himanshu Patni

Reputation: 195

add this in ngOnInit() if you have already added to index.html

(window as any).fbq('track', 'CompleteRegistration'); // this Worked for me

Upvotes: 2

Sourav Raj
Sourav Raj

Reputation: 159

create one service and call it in your app.component.ts

import { Injectable } from '@angular/core';

    @Injectable({
        providedIn: 'root'
    })
    export class FacebookPixelService {
        constructor() { }
        load() {
            (function (f: any, 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');
            (window as any).fbq.disablePushState = true; //not recommended, but can be done
            (window as any).fbq('init', '<your id>');
            (window as any).fbq('track', 'PageView');
        }
    }

Upvotes: 5

A. Beach
A. Beach

Reputation: 81

Even though fbq is globally-available in your app at runtime, the compiler doesn't know about it because it is defined in index.html (outside of the typescript files known to the compiler).

To fix this, add an ambient declaration to the files where you use fbq, like so:

declare const fbq: any; // 1. add an ambient declaration

@Component({...})
export class ComponentUsingFacebookPixel {

  fbq('track', 'CompleteRegistration'); // 2. This will compile now

} 

This doesn't change the compiled javascript or overwrite the value of fbq; it's a promise to the compiler that there will be a value by that name available at runtime.

You can provide a more specific type than any if you'd like additional help from the compiler, but any is sufficient to avoid the compilation error you're seeing.

Upvotes: 8

Related Questions