我正在构建视频组件,我需要获取源视频(源文件或容器)的尺寸,以将其传递给sibbling组件。我使用此代码:
//Video component
@Component({
moduleId: module.id,
selector: 'kt-media',
templateUrl: 'kt-media.component.html'
})
export class KT_MediaComponent implements AfterViewInit{
...
private ktIsMedia: boolean;
private ktMediaType: string;
@ViewChild('ktVideo') ktVideoElement;
constructor(private el: ElementRef, private renderer: Renderer) {
this.setMediaType();
}
ngAfterViewInit(){
this.ktVideoElement = this.getSize();
}
setMediaType(){
//This implementation works fine, I hide it for clarity of the problem
//Sets this.ktIsMedia to true and this.ktMediaType to 'video'
}
getSize():ktSize{
let w = this.ktVideoElement.nativeElement.videoWidth;
let h = this.ktVideoElement.nativeElement.videoHeight;
return {width: w, height: h}
}
}
这里是组件的模板:
<div *ngIf="ktIsMedia && ktMediaType === 'video'" >
<video
#ktVideo>
<source
[attr.src]="ktMediaSrc |safeUrl"
type="video/{{ktVideoType}}">
</video>
</div>
视频显示正确,但正在探索vs代码调试器,它显示ktVideoElement videoWidth和videoHeight为0.我尝试在不同的生命周期钩子上实现getSize():aferviewinit,oninit等...总是返回0作为视频的尺寸。是否可以获取源文件的尺寸或在视图中加载文件?如果是,我该如何实施呢?
答案 0 :(得分:2)
根据https://stackoverflow.com/a/4129579/217408,这应该有效:
<div *ngIf="ktIsMedia && ktMediaType === 'video'" >
<video (loadmetadata)="ktVideoElement = getSize()"
#ktVideo>
<source
[attr.src]="ktMediaSrc |safeUrl"
type="video/{{ktVideoType}}">
</video>
</div>
答案 1 :(得分:1)
根据Günter的回应,最终有效的是:
<div *ngIf="ktIsMedia && ktMediaType === 'video'" >
<video
#ktVideo
(loadedmetadata)="ktSize = getSize()">
<source
[attr.src]="ktMediaSrc |safeUrl"
type="video/{{ktVideoType}}">
</video>
</div>
我通过'loadedmetadata'更改'loadmetadat'并将视频标记放入,而不是源标记。