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 pile when I have this in my code as it can't find fbq
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 pile when I have this in my code as it can't find fbq
Share Improve this question edited Dec 6, 2019 at 5:17 zmag 8,25112 gold badges37 silver badges46 bronze badges asked Mar 5, 2018 at 22:24 James LewisJames Lewis 3031 gold badge3 silver badges6 bronze badges3 Answers
Reset to default 8Even though fbq
is globally-available in your app at runtime, the piler doesn't know about it because it is defined in index.html
(outside of the typescript files known to the piler).
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 pile now
}
This doesn't change the piled javascript or overwrite the value of fbq
; it's a promise to the piler 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 piler, but any
is sufficient to avoid the pilation error you're seeing.
create one service and call it in your app.ponent.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/en_US/fbevents.js');
(window as any).fbq.disablePushState = true; //not remended, but can be done
(window as any).fbq('init', '<your id>');
(window as any).fbq('track', 'PageView');
}
}
add this in ngOnInit()
if you have already added to index.html
(window as any).fbq('track', 'CompleteRegistration'); // this Worked for me