Miguel Miguel - 20 days ago 8
HTML Question

Get source dimensions of video tag in Angular 2

I'm building a video component and I need to get the dimensions of the source video(the source file or the container), to pass it to a sibbling component. I'm using this code:

//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}
}
}


Here the the template of the component:

<div *ngIf="ktIsMedia && ktMediaType === 'video'" >
<video
#ktVideo>
<source
[attr.src]="ktMediaSrc |safeUrl"
type="video/{{ktVideoType}}">
</video>
</div>


The video is shown correctly but exploring the vs code debugger, it shows that the ktVideoElement videoWidth and videoHeight is 0. I tryed to implement the getSize() on diferent lifecycle hooks: aferviewinit, oninit, etc... bus always return 0 as the dimensions of the video. Is posible to get the dimensions of the source file or once the file is loaded in the view? If it is, how can I implement it?

Answer

According to http://stackoverflow.com/a/4129579/217408 this should work:

<div *ngIf="ktIsMedia && ktMediaType === 'video'" >
    <video (loadmetadata)="ktVideoElement = getSize()"
        #ktVideo>
        <source 
            [attr.src]="ktMediaSrc |safeUrl" 
            type="video/{{ktVideoType}}">
    </video>
</div>