Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.:

  videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',...
  ];

To achieve this, I created a constructor like so:

  constructor(private sanitizer: DomSanitizer) {
    this.videos[this.trackByMethod(this.count)] = sanitizer.bypassSecurityTrustResourceUrl(this.videos[this.count]);
  }

In order to determine the position in the array, I implemented a method that retrieves the current index from the template:

  trackByMethod(index: number): number {
    return this.count = index;
  }

This is how my template is structured:

<div class="videos" align="center" *ngFor="let vid of videos; let i = index" [attr.data-index]="i" (ondrag)="trackByMethod(i)">
  <iframe [src] = "vid"  style='min-width: 30%; height: 315px' allowfullscreen>
  </iframe>
</div>

The issue I'm facing is that I am unable to retrieve the index from the template. The method trackByMethod with event binding

(ondrag)="trackByMethod(i)"
doesn't seem to work (I have tried various other interfaces of GlobalEventHandlers without success).

Could anyone offer assistance? Thank you!

Answer №1

Here is a suggestion:

      videoList: string[] = ['www.someURL1', 'www.someURL2',...
      ];
sanitizedVideos: SafeResourceUrl[];
    
    constructor(private sanitizer: DomSanitizer) {
this.sanitizedVideos =        this.videoList.map(video =>  sanitizer.bypassSecurityTrustResourceUrl(video);
      }

Implement the following in your HTML:

<div class="video-container" align="center" *ngFor="let vid of sanitizedVideos; let i = index" (ondrag)="trackByMethod(vid,i)">
  <iframe [src] = "vid"  style='min-width: 30%; height: 315px' allowfullscreen>
  </iframe>
</div>

Remember to utilize trackByMethod with both video and index parameters.

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

Angular and Bootstrap button collections

Incorporating Angular with Bootstrap, we have constructed a button group as shown below: <div class="input-group-append"> <div class="btn-group" role="group"> <button class="btn btn-sm btn-outline-sec ...

I am searching for the RowEnter and RowLeave events in a kendo-grid for Angular 2. Where can I find them

When using an ODATA bound Kendo UI Angular 2 table, I am facing the challenge of needing to save the data that a user edits inline on a per row basis instead of per cell. If only there were RowEnter and RowLeave events available for me to achieve this. Do ...

Dynamic tag names can be utilized with ref in TypeScript

In my current setup, I have a component with a dynamic tag name that can either be div or fieldset, based on the value of the group prop returned from our useForm hook. const FormGroup = React.forwardRef< HTMLFieldSetElement | HTMLDivElement, React. ...

Is it possible to streamline the process of importing all CommonModule modules during bootstrap with the new standalone feature in Angular?

I've recently started experimenting with Angular's standalone feature and module-less approach. However, I'm having trouble finding the information I need. From what I understand, in a standalone component you have to import any directives/ ...

What is the best way to retrieve a property from a conditional type using generics?

The code snippet above presents an issue in TypeScript: const exampleFn = function<AttributeName extends 'attributeA' | 'attributeB'>( whatToProcess: AttributeName extends 'attributeA' ? {attributeA: string} : {attri ...

Encountering the error "Unable to use the '+' operator with 'symbol' type when attempting to combine $route.name"

Looking to retrieve the current route name from a template in order to pass it to a router link (specifically passing the current route to the login view so I can redirect users there after authentication). Everything functions as expected, but when perfo ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Having issues with Angular CLI functionality

Recently, I have been diving into learning Angular 4. To start off, I installed Node.js and executed the following commands in the Node.js command prompt: npm install -g typescript npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__ ...

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

The Angular program is receiving significant data from the backend, causing the numbers to be presented in a disorganized manner within an

My Angular 7 application includes a service that fetches data from a WebApi utilizing EntityFramework to retrieve information. The issue arises when numeric fields with more than 18 digits are incorrectly displayed (e.g., the number 23434343434345353453,3 ...

Identifying changes in a property's value binding within Angular 4

One way to detect changes in a property decorated with @Input is by implementing the OnChanges interface: export class EmployeeComponent implements OnChanges { @Input() message: string; startDate: Date; ngOnChanges(changes: SimpleChanges) { fo ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Utilizing Regular Expressions in Angular 4 by Referencing Patterns Stored in an Object

I'm facing an issue where my code is functional, but I keep encountering a Tslint error that's proving difficult to resolve. This particular configuration worked fine with Angular 1, but now I'm in the process of migrating the application to ...

Error: Angular encountered an issue while loading the resource. Preflight response was not successful

I am attempting to send a request to an API endpoint using Angular in order to retrieve JSON data. Check out my code snippet below: import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http'; imp ...

The Twillio Chat Module is throwing an error with code TS1086, stating that an accessor cannot be declared in an

I encountered an issue with my Angular project that is version controlled and runs smoothly on a Windows machine. However, after pulling the changes to my Ubuntu 19 machine, I consistently receive an error related to the Twilio chat module: ERROR in node ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

What steps can be taken to resolve the error involving the preflight request failing to pass the access control check?

I'm currently working with angular code in one VM and node code in another. I am trying to make an API call from the angular VM to the node VM, and I have already included the cors module. However, when making the API call, I keep encountering the fol ...

Troubleshooting a ForwardRef issue in a TypeScript and React Native project

Encountering a ts error while using forwardRef. // [ts] Property 'forwardRef' does not exist on type 'typeof React'. const MyComponent = React.forwardRef((props: Props, ref: any) => ... An issue arises in React Native when the pare ...