I am writing a component where I need access to the <audio controls>
native element. I am doing it like this now by getting it in ngOnInit()
by using ElementRef
like this this.elementRef.nativeElement.querySelector("audio");
While it works I think it is very unelegant and Angular2 also warns of the risks when using ElementRef..
Is there really no simpler way?
Can I mark it as a local variable with <audio controls #player>
and somehow access the native element through this.player
or something similar from the controller?
import {Component, OnInit, ElementRef, Input} from 'angular2/core';
@Component({
selector: 'audio-preview',
template: `
<audio controls>
<source [src]="src" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
`
})
export class AudioPreview implements OnInit {
@Input() src: string;
constructor(public elementRef: ElementRef) {}
ngOnInit() {
var audioElement = this.getAudioElement();
audioElement.setAttribute('src', this.src);
}
getAudioElement() : HTMLAudioElement {
return this.elementRef.nativeElement.querySelector("audio");
}
}