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

后端 未结 1 541
你的背包
你的背包 2020-12-05 06:47

I am writing a component where I need access to the native element. I am doing it like this now by getting it in ngOnInit()

相关标签:
1条回答
  • 2020-12-05 07:30
    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题