Discover the steps to showcase a video within a Bootstrap modal using Angular 7

I am having trouble getting a video to autoplay when opening a Bootstrap modal. I have tried various methods without success. My approach involves clicking on an anchor tag that triggers a function to open the modal manually and dynamically set the video source. Can someone please assist me with this? The video plays fine without the modal.

This is how it works without the modal:

<video id="{{result.profileId._id}}" width="100%" height="200" controls style="margin:10px 0">
              <source src="{{result.url}}" poster="assets/images/avatar.png" type="video/mp4">
   </video>

HTML file:

<div class="col-md-6" *ngFor="let result of trendvideos">
        <div class="aud1 tr-vid card card-shadow">
            <div class="aud-blk"> 

             <a   (click)="getVideo(result.secureUrl)"   *ngIf="result?.profileId?.image.secureUrl != null" class="user-img mt-3" >
              <img class="img-fluid" src="{{result.profileId.image.secureUrl}}">
            </a>

            <a  (click)="getVideo(result.secureUrl)"   *ngIf="result?.profileId?.image.secureUrl == null" class="user-img mt-3">
              <img class="img-fluid" src="assets/images/avatar.png">
            </a>

            <p><b> {{ result.likes }} </b><span><i class="fas fa-heart" style="color: red;"></i></span></p>

          </div>
        </div>
      </div>

Modal code snippet:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <video id="video1" width="100%" height="200" controls autoplay style="margin:10px 0">
                <source  src="{{videoUrl}}" poster="assets/images/avatar.png" type="video/mp4">
              </video> 
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Save changes</button>
            </div>
          </div>
        </div>
  </div>

Typescript file for opening the modal:

getVideo(vidUrl) {
    //let videoid = event.getAttribute('data-value');
    console.log(vidUrl);
    this.videoUrl = vidUrl;
    $('#exampleModal').modal('show');
}

Answer №1

Incorporate the binding of bootstrap modal events within the ngOnInit() lifecycle hook. When the modal is shown, trigger the video to play using the 'play' jQuery function, and when the modal is closed, ensure that the video stops playing. It is important to utilize JQuery in your Angular project for this functionality.

$('#exampleModal').on('shown.bs.modal', function () {
   setTimeout(function() {
       $('#video1')[0].play();
   }, 1000);
  // or use below JS code if not using jQuery
 /* var vid = document.getElementById("video1"); 
  vid.play(); */

})
$('#exampleModal').on('hidden.bs.modal', function () {
  $('#video1')[0].pause();
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JsonFormatter is throwing an error because it is trying to access the property 'on' of an undefined variable

I have encountered an error while attempting to generate an HTML report using cucumber-html-reporter The error message is: Unhandled rejection TypeError: Cannot read property 'on' of undefined at new JsonFormatter (C:\path-to-project\ ...

What is the easiest method to conceal the initial button within a collection of buttons in an Angular2 template?

https://i.sstatic.net/j7XnN.png Within this section, I have a series of buttons, and I am looking to hide the first button in the list. What is the best way to accomplish this? Here is the HTML template I am working with: <section class="list-group ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...

Mat Progress Bar for Tracking Fetch API Requests and Generating XLS Files

I am interested in implementing a mat progress bar to track the progress made while fetching data from the database and creating an XLSX file. The progress does not need to be exact, rough estimates and sudden changes are acceptable. Is it feasible to achi ...

Refresh Angular to Ensure Accurate Printing

My Angular page is designed for user printing, featuring a large "Print" button. Upon clicking this button, I wish to hide it, print the page, and then display the button again. The initial state of the ToggleForPrint variable is false. <ng-container * ...

The property 'setParentKeyForNodeData' is not found in the 'Model' type. Perhaps you meant to use 'setCategoryForNodeData'?

As I work with gojs and utilize an organizational chart, I have encountered a problem with one of the context menus. Specifically, when selecting "Remove Role", I receive an error message stating Property 'setParentKeyForNodeData' does not exist ...

TypeScript - Using all interface keys as a custom type

https://i.sstatic.net/Bq80G.png How can the name type be defined so that the function getValue restricts its argument to only one of the key types in Data. ...

Rxjs: Sequentially perform a series of asynchronous operations and pause until all are completed

There exists a series of requests, in the form of URL strings, which need to be executed one after another and each subsequent request must wait until the previous one is complete. This sequence is necessary because every individual request has a high cost ...

Angular 2: Transformation of custom header names to lowercase

Angular 2 rc.6 implemented in typescript 2 I've developed a custom wrapper for the Http service to add specific headers. In the snippet below, options represents the RequestOptions object passed to Http.get(): //if content type is not specified, defa ...

Ways to delete an element from an array in MongoDB

I am a beginner in the MEAN stack development. I am currently working on implementing this and this. I have been using the $pull method, but it seems that it is not working for me. I suspect that the issue might be due to the differences in my MongoDB stru ...

Transitioning from Angular2 beta15 to beta16

After updating my package.json and running npm install, I encountered this error while trying to launch my app in the browser: angular2-polyfills.min.js:1 Unhandled Promise rejection: Error: Attempting to create a class provider but "undefined" is not a c ...

Badging with Angular, HTML, and Bootstrap

I've been attempting to integrate Bootstrap 5's badges into my Angular application, but they don't seem to be displaying correctly together. While using Angular 13, the html within the app-root component appears clustered without proper for ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

Troubleshooting: Why is my Angular Ionic Reactive Form not showing up on the

I'm currently experiencing an issue with my Angular/Ionic form, where the form controls are not displaying correctly on the web. My goal is to create a dynamic form that allows users to input the number of groups and students for each year. However, w ...

What is the best way to avoid curly braces in an Angular template?

If I need to show the following string, including the {{ }}, in an Angular 2+ template: Hello {{name}}, how are you?" Note: The entire string will be hardcoded, not from a variable. What is the optimal method to encode the curly braces so they are not ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...