Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datalayer.push with Typescript in Angular 6

When I click on button, I should send into datalayer information, but I don't know how to do it, because I'm using Angular 6, so I need to use Typescript and window.dataLayer.push not working and give me this error

enter image description here

Form

<form>
            <div class="radio">
              <input value="Yes" id="radio-1" [(ngModel)]="answer" name="radio" type="radio">
              <label class="radio-label rob-l" for="radio-1">Yes</label>  
          </div>
          <div class="radio">
            <input value="No" id="radio-2" [(ngModel)]="answer" name="radio" type="radio">
            <label class="radio-label rob-l" for="radio-2">No</label>
          </div>
          </div>
        <div class="btn">
          <button (click)="Next()" type="submit">Next question</button>
        </div>
      </form>

And I want to recieve smth like that

Next(){
    if ((this.path == 1) && (this.answer === "Yes" || this.answer === "No"))
          {
            // window.dataLayer = window.dataLayer || [];
            // window.dataLayer.push({
            // 'event': 'answer',
            // 'answer': this.answer 
            // });
            this.path++;
            this.answer = "";
          }
}

Problem solved with this code:

window['dataLayer'] = window['dataLayer'] || [];
        window['dataLayer'].push({
        'event': 'Answer',
        'failedText': this.answer 
        });
    ngOnInit() {
        window['dataLayer'] = window['dataLayer'] || {};
      }
like image 562
Aleksey Dyomin Avatar asked Oct 09 '18 13:10

Aleksey Dyomin


People also ask

How do I push an event into dataLayer?

The syntax for sending an event with dataLayer.push() is as follows: dataLayer.push({'event': 'event_name'});

What does the dataLayer push () command return?

The return value, assuming you are referring to when you pasted the code into the console, indicates whether a GTM tag fired in response to the push. "true" means that no tags fired, and "false" means that a tag fired.

What is GTAG dataLayer?

Google Tag Manager functions best when deployed alongside a data layer. A data layer is a JavaScript object that is used to pass information from your website to your Tag Manager container. You can then use that information to populate variables and activate triggers in your tag configurations.


1 Answers

You can can declare global Window interface with dataLayer property on top of yout component/service ect., like this:

// Declare gTM dataLayer array.
declare global {
  interface Window { dataLayer: any[]; }
}

And then just use that property in the code of your component without any errors.

like image 63
Victor Avatar answered Oct 13 '22 00:10

Victor