title: Angular2: What is the best way to get a reference of a template element
body: <p>Let's say I have a component like this in Angular 2.</p>
  
  <pre><code>@Component ({
     directives: [Timeline, VideoPlayer],
     template: `&lt;div&gt;
      &lt;span id="myId"&gt;&lt;/span&gt;
      &lt;videoplayer [mode]="mode"&gt;&lt;/videoplayer&gt;
      &lt;timeline [mode]="mode"&gt;&lt;/timeline&gt;
    &lt;/div&gt;`,
  })
  export class VideoEditor {
  }
  </code></pre>
  
  <p>How can I get a reference to an element from a template? For instance, how do I get a reference to a <code>&lt;span&gt;</code>?</p>
  
  <p>I found two approaches so far:</p>
  
  <p>1) Get a reference using <a href="https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html" rel="noreferrer">ElementRef</a></p>
  
  <pre><code>export class VideoEditor {    
    constructor (private el: ElementRef) {
      el.nativeElement.getElementsBy.....;
    }
  }
  </code></pre>
  
  <p>2) Using <a href="https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html" rel="noreferrer">ViewChild</a></p>
  
  <pre><code>export class VideoEditor {  
    @ViewChild(Timeline) timeline: Timeline;  
    ngAfterViewInit () {
      this.timeline;
    }
  }
  </code></pre>
  
  <p>3) Using <a href="https://angular.io/docs/ts/latest/guide/template-syntax.html#!#local-vars" rel="noreferrer">local template variable</a></p>
  
  <hr>
  
  <p>1) What I don't like about a first approach is that I need to do <code>getElementsBy...</code>-like function.</p>
  
  <p>2) Regarding a second one, I don't know how to get an access to a HTML element, I can only get access to another sub-component. And what if I have more subcomponents of a same type?</p>
  
  <p>3) Local template variable only works within a templates, am I right? </p>
  
  <p>What is the best way to get a reference to a template in Angular 2?
  I'd like to have something like React has
  <a href="https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute" rel="noreferrer">https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute</a></p>
  
  <pre><code>&lt;input ref="myInput" /&gt;
  </code></pre>
  
  <hr>
  
  <pre><code>var input = this.refs.myInput;
  var inputValue = input.value;
  var inputRect = input.getBoundingClientRect();
  </code></pre>