I use the Youtube Angular pakacge in my Angular 11 project. I would like to fill the player to 100% of the divs height, which is a TailWind h-full div:
<div class="flex flex-col flex-auto w-full h-full xs:p-2" #videoContainer>
<youtube-player
*ngIf="videoId"
[videoId]="videoId"
width="100%"
[height]="videoHeight"
></youtube-player>
</div>
I tried to do this in two different eays already:
height="100%" or height="100vh"Both leads to:

[height]="videoHeight"
ngOnInit() {
this._params = this._route.params.subscribe((params) => {
this.videoId = params['videoId'];
});
}
ngAfterViewInit(): void {
this.videoHeight = this.videoContainer.nativeElement.offsetHeight;
}
This works, but leads to
Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '905'..
videoHeightI moved this.videoHeight = this.videoContainer.nativeElement.offsetHeight; to the constructor and in the OnInit this leads to:
TypeError: Cannot read property 'nativeElement' of undefined at new YoutubeComponent
What am I doing wrong?
Here is how I solved it, I created new component:
ng g component components/yt-player
In yt-player.component.html add container with ref and youtube-player
<div #youTubePlayer >
<youtube-player [width]="videoWidth" [height]="videoHeight" [videoId]="videoID"></youtube-player>
</div>
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 {
this.onResize();
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(
this.youTubePlayer.nativeElement.clientWidth,
1200
);
// so you keep the ratio
this.videoHeight = this.videoWidth * 0.6;
this.changeDetectorRef.detectChanges();
}
}
The code is basiclly self explenatory, you have refrence on the container of youtube-player, in afterViewInit you set videoHeight and videoWidth, to corespond to the width of the container. We set up 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With