Search code examples
javascriptangulartypescriptembedvimeo

How to embed vimeo video in angular component?


I have a angular 8 application. and I try to embed a vimeo video.

So I have for the ts like this:

getVideoId(url, prefixes) {
    const cleaned = url.replace(/^(https?:)?\/\/(www\.)?/, '');
    for (let i = 0; i < prefixes.length; i++) {
      if (cleaned.indexOf(prefixes[i]) === 0) {
        return cleaned.substr(prefixes[i].length);
      }
    }
    return undefined;
  }

  getVimeoId(url) {
    return this.getVideoId(url, ['vimeo.com/', 'player.vimeo.com/']);
  }

 getVideoSafeUrl(url: string): SafeResourceUrl {

    const embedUrl = this.parseYoutubeUrl(url);
    const safeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(
      this.parseVimeo(embedUrl));

   return safeUrl;
  }

and template like this:

 <iframe
            *ngIf="videoUrl.value"
            class="video-iframe"
            type="text/html"
            [src]="getVideoSafeUrl(videoUrl.value)"
            frameborder="0"
            allowfullscreen
          ></iframe>

But so when I try to insert vimeo video: https://vimeo.com/346340496/11432ab1db

I get this error:

VM7131 vendor.js:76269 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '346340496'
Error: Cannot match any routes. URL Segment: '346340496'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2432)
    at CatchSubscriber.selector (router.js:2413)
    at 

So what I have to change?

Thank you


Solution

  • Try not:

    https://vimeo.com/346340496/11432ab1db
    

    but in below url format when using as [src] in iframe

    https://player.vimeo.com/video/346340496
    

    You need to write the parser accordingly , something like

      function  parseVimeo(url) {
        const re = /\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i;
        const matches = re.exec(url);
        return matches && "https://player.vimeo.com/video/"+matches[1];
      }
    
    

    Make sure you have tested it for all urls and not just https://vimeo.com/346340496/11432ab1db . Put proper user messages when there are some unknown urls as well