title: Angular 4 get dom element
body: <p>Hi i'm trying to set focus on an input element once the edit button is clicked on an Angular 4 application. </p>
  
  <p>First i tried Renderer2, but it doesn't seem to work for this purpose.</p>
  
  <p>Now I'm trying to get it using @ViewChild, I'm always getting value as undefined. </p>
  
  <p>I event tried implementing AfterViewInit and logging the element immediately once loaded, but still I'm getting 'undefined'. Please help..</p>
  
  <pre><code>        import { Component, OnInit, Input, Output, EventEmitter, Renderer2, ViewChild, AfterViewInit } from '@angular/core';
          import { NgIf } from '@angular/common';
          import { DataService } from '../data.service';
          import { NgForm } from '@angular/forms';
  
          @Component({
              selector: 'app-artist-list-item',
              template: `
                      &lt;button class="w3-button w3-circle w3-orange" (click)="edit(nameInput)"&gt;&lt;i class="fa fa-pencil"&gt;&lt;/i&gt;&lt;/button&gt;
                      &lt;span *ngIf="editable"&gt;
                          &lt;input  class="name" #nameInput (keyup)="onKey(nameInput.value)" (keypress)="inputEnter($event)" [value]="artist.name"&gt;
                          &lt;button class="w3-button w3-green btn-save" (click)="save()"&gt;Save&lt;/button&gt;
                      &lt;/span&gt;
                      &lt;span *ngIf="!editable"&gt;
                          {{artist.name}}
                      &lt;/span&gt;
              `,
              styleUrls: ['./artist-list-item.component.scss']
          })
          export class ArtistListItemComponent implements OnInit, AfterViewInit {
  
              @Input() artist: any;
              @Output() onDelete = new EventEmitter();
              @Output() onEdit = new EventEmitter();
              @Output() onSave = new EventEmitter();
              @ViewChild('nameInput') nameInput;
  
              public editable: boolean = false;
              name: any = '';
  
              constructor(private Data: DataService, private rd: Renderer2) { }
  
              ngAfterViewInit() {
                  console.log(this.nameInput);
              }
  
              ngOnInit() {
              }
  
              edit(el) {
                  console.log(el);
                  console.log(this.nameInput);
                  this.editable = true;
                  this.name = this.artist.name;
              }
  
          }
  </code></pre>
  
  <p>by the way i have removed the code where i tried to set focus.</p>
  
  <pre><code>            edit(el) {
                  console.log(el);
                  console.log(this.nameInput);
                  this.nameInput.focus();
                  this.editable = true;
                  this.name = this.artist.name;
              }
  </code></pre>