Recently I had the same problem like you and could not find any solution in the internet so I coded my own cookie dialog for Angular.
Instead of loading the google analytics script in the index.html, I defined a script loader which loads the script if the consent dialogue is accepted.
The script loader looks like the following:
public loadScript() {
let body = <HTMLDivElement> document.body;
let script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.googletagmanager.com/gtag/js?id=ENTER TAG';
script.async = true;
script.defer = true;
enter code here`body.appendChild(script);
}
And the full logic if the cookie is accepted is the following:
public accept(): void {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (typeof gtag !== 'undefined') {
gtag('config', 'ENTER TAG', {
page_path: event.urlAfterRedirects,
});
}
}
});
this.loadScript();
this.googleAnalyticsService.eventEmitter('TEST', 'User visited page',
"User visited page" , 'accept dialog', 1);
this.sharedService.acceptedConsent = true;
this.setConsent(true);
this.closePopup = true;}
It works like the following:
User clicks accept in the frontend ui, then GA is configured, the necessary script loaded , an event is emitted that shows that a user visited the page and the session storage saves that cookies are allowed and the pop up is closed.
If the user denies the cookies then the scripts are never loaded and no connection is established to Google.
If the user revokes the cookies I set the session storage variable to false and delete all the cookies and reload the page.
Hope I helped you somehow.
I made my cookie dialog open source here: https://github.com/eduardfrankford/GoogleAnalytics_CookieDialogue_Angular13