Search code examples
angularangular-materialyoutubecomponents

How to autoplay youtube component in Angular?


I am using Angular 11 with Angular Youtube Component, but i just don't figure it out how to autoplay it on showing the player without playing it manually Please Can anyone help me?

     <youtube-player  
        [videoId]="'wZti8QKBWPo'" 
        [playerVars]="{controls: 0, mute: 1, autoplay: 1}"
        (ready)="onReady($event)"
        [startSeconds]="30"
        [width]="width"
        [height]="height">
    </youtube-player>

when i pass the extra configs [playersVars] to player component, the only property works is the controls property, the rest nothing, i tried to bind from the ts file instead of passing object literal in the html file, then the mute property also works along the controls,


Solution

  • I have checked an example again and it works. The one reason that it doesn't work it's startSeconds property. Somehow, when we add this property it stops to autoplay the video. But without it, it works well.

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      template: `
        <youtube-player
          [playerVars]="playerConfig"
          [width]=640
          [height]=320
          [videoId]="videoId"
          (ready)="onReady($event)"
        ></youtube-player>
      `,
      selector: 'app-video'
    })
    export class VideoComponent implements OnInit {
      playerConfig = {
        controls: 0,
        mute: 1,
        autoplay: 1
      };
      videoId = 'XqZsoesa55w';
      ngOnInit() {
        const tag = document.createElement('script');
    
        tag.src = 'https://www.youtube.com/iframe_api';
        document.body.appendChild(tag);
      }
    
      onReady(e): void {
        console.log(e, 'its ready')
      }
    }
    

    Here is a working example of app.