Angular ng-boostrap modal automatically refreshes upon detecting mouse movement with an embedded video

Currently, I am facing an issue with my Angular 7 ng-bootstrap modal. The problem arises when the modal, which includes a video player within an <iframe>, is moved to the production system. Whenever there is any mouse movement detected, the video gets reloaded, causing inconvenience.

In an attempt to resolve this issue, I implemented a directive to capture mouse events and prevent the reloading of the video.

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[mt2StopMouseEvents]'
})

export class StopMouseEventsDirective {

  @HostListener('mouseover', [ '$event' ])
  public onMouseover(event: any): void {
    console.log(`onMouseOver\t${JSON.stringify(event)}`);
    event.stopPropagation();
  }
  @HostListener('mousemove', [ '$event' ])
  public onMousemove(event: any): void {
    console.log(`onMousemove\t${JSON.stringify(event)}`);
    event.stopPropagation();
  } 
  @HostListener('mouseleave', [ '$event' ])
  public onMouseleave(event: any): void {
    console.log(`onMouseleave\t${JSON.stringify(event)}`);
    event.stopPropagation();
  }
  @HostListener('mousemout', [ '$event' ])
  public onMouseout(event: any): void {
    console.log(`onMouseout\t${JSON.stringify(event)}`);
    event.stopPropagation();
  }
  constructor() { }
}

The directive is applied to the modal like so:

<div class="modal-content" mt2StopMouseEvents  >
    <div class="modal-header bg-success">
        <h3 class="modal-title ">{{title}}</h3>
        <button type="button" class="btn btn-light" (click)="activeModal.dismiss('Close click')">Close</button>
    </div>
    <div class="modal-body">
        <iframe height="100%" width="100%" [src]="getURL()"></iframe>
    </div>
</div>

Here is a brief overview of the help model component structure:

import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'mt2-help',
    templateUrl: './myHelp.component.html',
    styleUrls: [ './myHelp.component.scss' ],
})

export class MyHelpComponent implements OnInit {
    @Input() title;
    @Input() helpURL;

    constructor(
        private sanitizer: DomSanitizer,
        public activeModal: NgbActiveModal
    ) { }

    ngOnInit() {
    }

    getURL(): SafeResourceUrl {
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.helpURL);
    }
}

Despite capturing the events successfully, the video still reloads. Below is a snippet from the console log for reference:

onMousemove {"isTrusted":true} stop-mouse-events.directive.ts:26 
onMouseleave {"isTrusted":true} stop-mouse-events.directive.ts:11 
onMouseOver {"isTrusted":true} stop-mouse-events.directive.ts:16

I appreciate any assistance provided. Thank you.

Answer №1

It seems that the issue with the lifecycle hooks was due to interference from mouse movement, causing the DOM to validate against any changes it detected. To resolve this, I relocated the url sanitizer function to 'ngOnInit' and stored it as a private variable. When requested by the template, the variable is then returned. Additionally, I removed the directive from the template that I initially created in an effort to prevent event propagation.

The updated class now appears as follows:

import { Component, OnInit, Input }      from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';


import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector:    'mt2-help',
    templateUrl: './myHelp.component.html',
    styleUrls:   [ './myHelp.component.scss' ],

})

export class MyHelpComponent implements OnInit {


    @Input() title;
    @Input() helpURL;

    private _helpURL: SafeResourceUrl;

    constructor(
        private sanitizer: DomSanitizer,
        public activeModal: NgbActiveModal
    ) { }

    ngOnInit() {
        this._helpURL = this.sanitizer.bypassSecurityTrustResourceUrl(this.helpURL);
    }

    getURL(): SafeResourceUrl {
        return this._helpURL;
    }
}

I would like to express my gratitude to Max Koretskyi (also known as Wizard) for his insightful article "A gentle introduction into change detection in Angular" and accompanying YouTube video, which guided me towards the right solution.

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

Incorporate a Font Awesome button in front of the content of each list group item in Pug/Jade

I'm struggling to insert a Font Awesome icon before the list-group-item content within a Pug loop, but I can't seem to make it work. Adding the icon at the end of the list-group-item content is straightforward. How do I position it in front (I h ...

Alter value upon click using JavaScript switch statement

I have an array that was downloaded from PHP to JS with paths to images. I am trying to switch the value on clicking the arrow image, -1 for left and +1 for right. However, my code is not working as expected. <script> var urls = <?php echo jso ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...

Exploring Object Elements using For Loop

After trying numerous methods, I am still puzzled by this issue. I have a feeling that the solution is going to be something very simple, but nevertheless, I need to ask for help. This is the function I'm dealing with: Module.load = function(a) { ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

Launch a modal from a separate webpage

I've been trying to implement a modal using Bootstrap 4, and after referring to the documentation, it seems to be working smoothly. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <scri ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container. To better illustrate my problem, you can view a demo on Fid ...

Dynamically incorporating Angular UI Datepicker into your project

For my project, I am required to include a dynamic number of datepickers on the page. I attempted to accomplish this using the following method (Plunker): Script: var app = angular.module('plunker', ['ui.bootstrap']); app.controll ...

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

Tips for assigning an ID to a span element within a for loop

I am facing a challenge where I need to assign IDs to span tags that do not have the id attribute. These IDs need to be assigned sequentially by incrementing through a for loop and passing my geneologicalSequenceNumber into each span tag. Can you guide me ...

Learn the process of making an http request in Angular 8 by utilizing FormData

After struggling with sending data from my html form to the backend server using Angular HTTPClient, I realized that my code was not working as expected. HTML Form <form class="border text-center p-5 reg-frm" [formGroup]="ContactusForm"> <l ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

The error message "Type 'Observable<void>' cannot be assigned to type 'void | Action | Observable<Action>' when integrating an effect" is displayed

Encountering an error when trying to add effects using the 'run' method. Attempted to manually return a string, number, and other types, but nothing seems to work. Here is the effects code snippet: @Effect() getRoles$: Observable<Roles[]> ...

The Angular SSR feature is throwing errors due to non-ESM modules present in my Express API implementation

In my Angular SSR project, I have set up my Express API to run as part of the SSR service. The app code is located in /src/app, while the API code resides in /src/api. There are some imports of the API code into the app code, primarily for using the same t ...

Angular Component not reflecting changes to property when array is reversed

Within my Angular Component, I have a public array variable that is initially set to an empty array. Upon receiving a response from a service in the constructor, I attempt to update the array by using this.variable = array.reverse(). However, instead of ...

"Utilizing datatables to efficiently submit form data to the server-side

I'm curious for those who utilize the Datatables javascript plugin, is there a way to replicate this specific example using server-side data? The current example I came across has its data hardcoded directly in the HTML. ...

Having trouble retrieving accurate JSON data from an excel workbook

Currently, I am utilizing the npm module xlsx for the purpose of writing and reading JSON data. My goal is to take this JSON data and write it into an Excel file: { "name": "John", "class": 1, "address" : [ { "street": "12th Cross", "city": "London" }, { ...