这是我解决问题的方法, 我创建了新组件:
ng g component components/yt-player
在
yt-player.component.html
添加带有 ref 和 youtube-player
的容器
<div #youTubePlayer >
<youtube-player [width]="videoWidth" [height]="videoHeight" [videoId]="videoID"></youtube-player>
</div>
并在
yt-player.component.ts
中添加以下代码:
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();
}
}
代码基本上是不言自明的,您可以参考 youtube-player 的容器,在 afterViewInit 中设置
videoHeight
和 videoWidth
,以对应容器的宽度。我们设置事件监听器在尺寸改变的情况下更新宽度和高度。最后我们添加 @Input('videoID') videoID: string
这样我们就可以将 id 传递给 youtube-player 组件。所以我们可以这样使用它:
<yt-player videoID="oHg5SJYRHA0"></yt-player>
height="100vh"
videoHeight
中为 constructor
赋值
或在 ngOnInit
挂钩中。 <youtube-player
[videoId]="videoId"
[width]="screenWidth"
[height]="screenHeight"
></youtube-player>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: 'your-component.page.html',
styleUrls: ['your-component.page.scss'],
})
export class YourComponent implements OnInit {
screenWidth: number;
screenHeight: number;
ngOnInit() {
this.screenWidth = window.innerWidth;
this.screenHeight = window.innerHeight * 0.3; // 30% of the viewport height
}
}
删除模板代码中设置
width
和 height
的任何尝试 -
<div class="flex flex-col flex-auto w-full h-full xs:p-2">
<youtube-player *ngIf="videoId" [videoId]="videoId"></youtube-player>
</div>
也来自组件代码。然后它应该自动显示为全高。