问题
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");
}
}
回答1:
- Use @ViewChild to access some element in the view.
- Use [attr.src] to creating binding to 'src' attribute of an element.
- Use Renderer if for some reason you need to change the DOM imperatively.
See this plunk.
import {Component, Input, ViewChild, Renderer} from 'angular2/core';
@Component({
selector: 'audio-preview',
template: `
<audio controls #player [attr.src]="src">
<source [src]="src" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
`
})
export class AudioPreview {
@Input() src: string;
@ViewChild('player') player;
constructor(public renderer: Renderer) {}
ngAfterViewInit() {
console.log(this.player);
// Another way to set attribute value to element
// this.renderer.setElementAttribute(this.player, 'src', this.src);
}
}
来源:https://stackoverflow.com/questions/34517969/access-a-local-variable-from-the-template-in-the-controller-in-angular2