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

  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);
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)