从Angular2中的控制器中的模板访问局部变量

sko*_*and 34 angular

我正在编写一个组件,我需要访问本<audio controls>机元素.我现在正在做它像这样通过获取它ngOnInit()通过使用ElementRef这样的this.elementRef.nativeElement.querySelector("audio");

虽然它有效,但我认为它非常不优雅,Angular2也警告使用ElementRef时的风险.

真的没有更简单的方法吗?

我可以将它标记为局部变量,<audio controls #player>并通过this.player某种方式从控制器访问本机元素或类似的东西吗?

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*ods 59

  1. 使用@ViewChild访问某些元素在视图中.
  2. 使用[attr.src]创建结合的元素的"SRC"属性.
  3. Renderer如果出于某种原因需要使用必须更改DOM.

看到这个插件.

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);
  }
}
Run Code Online (Sandbox Code Playgroud)