12

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'] || {};
      }
Aleksey Dyomin
  • 143
  • 1
  • 1
  • 9
  • What exactly is not working? Do you get a compile error? A runtime error? Does nothing show up in the array? – Mathyn Oct 09 '18 at 13:12
  • Changed my question – Aleksey Dyomin Oct 09 '18 at 13:17
  • 2
    Possible duplicate of [How do you explicitly set a new property on \`window\` in TypeScript?](https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript) – SiddAjmera Oct 09 '18 at 13:24
  • 1
    @SiddAjmera has the right idea. In essence you should define the property 'dataLayer' as being part of the window object. Or alternatively cast the window object to type 'any' to silence the errors. – Mathyn Oct 09 '18 at 13:26

2 Answers2

9

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.

Victor
  • 99
  • 1
  • 2
0

In your marketo-form.services.ts file declare the window const and use it on the submit function.

declare let MktoForms2: any;

declare const window: Window & { dataLayer: Record<string, unknown>[] };

form.onSubmit(function () {
            window.dataLayer.push({
              event: `form_fill_success_` + formId,
            });
          });
Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25