Pri*_*muS 3 css youtube angular
我在 Angular 11 项目中使用Youtube Angular pakacge。我想将播放器填充到 div 高度的 100%,这是一个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>
Run Code Online (Sandbox Code Playgroud)
我已经尝试以两种不同的方式做到这一点:
height="100%"或height="100vh"[height]="videoHeight"
ngOnInit() {
this._params = this._route.params.subscribe((params) => {
this.videoId = params['videoId'];
});
}
ngAfterViewInit(): void {
this.videoHeight = this.videoContainer.nativeElement.offsetHeight;
}
Run Code Online (Sandbox Code Playgroud)
这有效,但会导致
错误:NG0100:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。先前值:“未定义”。当前值:“905”..
videoHeight我转移this.videoHeight = this.videoContainer.nativeElement.offsetHeight;到构造函数并在其中OnInit导致:
类型错误:无法读取新 YoutubeComponent 中未定义的属性“nativeElement”
我究竟做错了什么?
小智 7
这是我解决它的方法,我创建了新组件:
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>
Run Code Online (Sandbox Code Playgroud)
并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();
}
}
Run Code Online (Sandbox Code Playgroud)
该代码基本上是不言自明的,您可以参考 youtube-player 的容器,在 afterViewInit 中设置videoHeight和videoWidth,以对应容器的宽度。我们设置事件监听器在尺寸改变的情况下更新宽度和高度。最后我们添加,@Input('videoID') videoID: string以便我们可以将 id 传递给 youtube-player 组件。所以我们可以这样使用它:
<yt-player videoID="oHg5SJYRHA0"></yt-player>