0

I'm trying to use YouTube iFrame API in angular2 but I run into a problem.

let onStateChange = (state) => {
    if (state.data === window['YT'].PlayerState.PLAYING) {
        console.log("window['YT'].PlayerState.PLAYING");
        this.isPlaying = true;
    }
    if (state.data === window['YT'].PlayerState.PAUSED) {
        console.log("window['YT'].PlayerState.PAUSED");
        this.isPlaying = false;
    }
};

and then

this.player = new window['YT'].Player("video-player", {events: { onStateChange } });

Callbacks handling the player events are executed but views don't get updated.

Here is the view:

<button class="control" (click)="play()" *ngIf="!isPlaying">Play</button>
<button class="control" (click)="pause()" *ngIf="isPlaying">Pause</button>

When I click on "Play", the video plays but the "Pause" button doesn't show up (the "Play" button doesn't disappear either).

When I click once again on the - not hidden - "Play" button, the video keeps playing and the "Play" button is replaced by "Pause". So it works the second time.

I googled it already but didn't find a solution:

Community
  • 1
  • 1
David
  • 4,785
  • 7
  • 39
  • 63

1 Answers1

0

I just found the solution.

Import NgZone

import { ..., NgZone } from '@angular/core';

Add NgZone as a property

constructor(private ngZone: NgZone) {}

And then

let onStateChange = (state) => {
    this.ngZone.run(() => { // This was the trick
        if (state.data === window['YT'].PlayerState.PLAYING) {
            this.isPlaying = true;
        }
        if (state.data === window['YT'].PlayerState.PAUSED) {
            this.isPlaying = false;
        }
    });
};

this.player = new window['YT'].Player("video-player", { events: { onStateChange } });
David
  • 4,785
  • 7
  • 39
  • 63
  • Do you have a link to the whole code? I'm struggling to get the iframe api with angular 2 running. – Saerdn Dec 01 '16 at 19:34