Home > Software engineering >  How to play a youtube video when an image is clicked in angular
How to play a youtube video when an image is clicked in angular

Time:08-24

I am developing a website where-in, i want a youtube video to be played when i click on the image. I don't want to go to the new tab for playing the video.

And I want the video to be placed exactly in the background of the image. When i click the image, the video should be played hiding the image.

Can anyone suggest me how to achieve this using html, css

CodePudding user response:

You can simply add a property, which you can set as a boolean or any. Then you can create a method() to change the value of that property by clicking.

export class AppComponent  {
  isVideo : any = {};

  OnChange(){
    this.isVideo = !this.isVideo
  }
}

Then in the template you can make 2 divs. One div contains your image. Other will contain video. Then you can use *ngIf="isVideo" to switch the div on click.

<div  *ngIf="isVideo">
  <img
    src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg"
    alt=""
    (click)="OnChange()"
  />
</div>
<div  *ngIf="!isVideo">
  <iframe
    src="https://www.youtube.com/embed/OP7IdmB9Dlg?autoplay=1&loop=1&autopause=0&muted=1"
    allow="autoplay"
    width="640"
    height="360"
    frameborder="0"
    webkitallowfullscreen
    mozallowfullscreen
    allowfullscreen
  >
  </iframe>
</div>
  

Here is the working Demo.

Note : You can also disable the autoplay function of the video if you want.

  • Related