DEV Community


Posted on

How to make width of Angular youtube-player responsive

If you are working with Angular modal for integration of youtube videos, there is a chance that you got stuck just like me on the making size of embedded youtube player full width of the parent. The problem is that the youtube-player component accepts width and heigh only as a number, that is as pixels, which is not good for the responsive design. It is nothing complicated but I will just document it for easier finding in the future.

Let’s start by creating a new component that will have a container for the youtube-player:

ng g component components/yt-player

In yt-player.component.html add container with ref and youtube-player

<div #youTubePlayer>
Enter fullscreen mode Exit fullscreen mode

and in yt-player.component.ts add this code:

export class YtPlayerComponent implements AfterViewInit {
  @ViewChild("youTubePlayer") youTubePlayer: ElementRef<HTMLDivElement>;

  videoHeight: number | undefined;
  videoWidth: number | undefined;

  @Input("videoID") videoID: string;

  constructor(private changeDetectorRef: ChangeDetectorRef) {}

  ngAfterViewInit(): void {
    window.addEventListener("resize", this.onResize.bind(this));

  onResize(): void {
    // you can remove this line if you want to have wider video player than 1200px
    this.videoWidth = Math.min(
    // so you keep the ratio
    this.videoHeight = this.videoWidth * 0.6;
Enter fullscreen mode Exit fullscreen mode

The code is basically self-explanatory, you have reference on the container of youtube-player, in afterViewInit you set videoHeight and videoWidth, to correspond to the width of the container. We set up an event listener in the case of size changes to update the width and height. And in the end, we add @Input('videoID') videoID: string so we can pass the id to the youtube-player component. So we can use it like this:

<yt-player videoID="oHg5SJYRHA0"></yt-player>

Thank for reading and if you have any suggestions, please leave a comment.

Top comments (0)