Search code examples
angularionic-frameworkcapacitor

Pass id in Videos Slideshow in Angular 12


I have created a video slideshow in my Ionic 5 Angular 12 project. I have also created a play/pause button so that the user may play or pause each video. But everytime i tap in one video, all videos play not only one. I guess i need to pass the id of the video to the .ts play/pause function, right? Or is there any other way?

html. media are the video (object) parameters like id, name etc...

<ion-slide *ngFor="let media of medias | filterByType: mediaType; let i = index">
<ng-container>
<div class="container" (click)="playVideo()">
    <video autoplay="autoplay" webkit-playsinline="true" playsinline="true"
       onloadedmetadata="this.muted=true" class="fillWidth" preload="metadata" 
       #video>
        <source [src]="media?.image_path" [type]="'video/webm'">
        <source [src]="media?.image_path" [type]="'video/mp4'">
        <source [src]="media?.image_path" [type]="'video/ogg'">
    </video>
 </div>
 </ng-container>
 </ion-slide>

.ts

export class HomePage implements OnInit {
@ViewChild('video') myVideo: ElementRef;

  isplay = false;


 playVideo(){
    if(this.isplay){
        this.myVideo.nativeElement.pause();
    }
    else{
        this.myVideo.nativeElement.play();
    }  
    this.isplay=!this.isplay
  }

Any help? Thanks


Solution

  • You can still use js code in your project and access DOM directly (remember to use it with caution). Try something like:

    <ion-slide *ngFor="let media of medias | filterByType: mediaType; let i = index">
    <ng-container>
    <div class="container" (click)="playVideo('video'+i)">
        <video autoplay="autoplay" webkit-playsinline="true" playsinline="true"
           onloadedmetadata="this.muted=true" class="fillWidth" preload="metadata" 
           [id]="'video'+i">
            <source [src]="media?.image_path" [type]="'video/webm'">
            <source [src]="media?.image_path" [type]="'video/mp4'">
            <source [src]="media?.image_path" [type]="'video/ogg'">
        </video>
     </div>
     </ng-container>
     </ion-slide>
    

    .ts:

     playVideo(id: string){
            if(this.isplay){
                (document.getElementById(id) as HTMLMediaElement).pause();
            }
            else{
                (document.getElementById(id) as HTMLMediaElement).play();
            }  
            this.isplay=!this.isplay
          }
    

    You have many elements so probably you need to store isplay for each one of them, or pause the previous video before playing new one.