Access a local variable from the template in the controller in Angular2

浪子不回头ぞ 提交于 2019-11-26 19:57:33

问题


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:


  1. Use @ViewChild to access some element in the view.
  2. Use [attr.src] to creating binding to 'src' attribute of an element.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!