Acceda a una variable local desde la plantilla en el controlador en Angular2
Estoy escribiendo un componente donde necesito acceso al elemento nativo <audio controls>
. Lo estoy haciendo así ahora al obtenerlo en ngOnInit()
usando ElementRef
así this.elementRef.nativeElement.querySelector("audio");
Mientras funciona creo que es muy poco elegante y Angular2 también advierte de los riesgos al usar ElementRef..
¿No hay realmente una manera más simple?
Puedo marcarlo como una variable local con <audio controls #player>
y de alguna manera acceder al elemento nativo a través de this.player
o algo similar desde el controlador?
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");
}
}
33
1 answers
- Uso
@ViewChild
para acceder a algún elemento de la vista. - Uso
[attr.src]
crear un enlace al atributo ' src ' de un elemento. - Uso
Renderer
si por alguna razón necesita cambiar el DOM imperativamente.
Ver este 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);
}
}
58
Author: alexpods,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-04 13:29:19
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-04 13:29:19