title: Angular6 AutoFocus using *ngIf
body: <pre><code>&lt;div class="dropdownContainer" placeholder="test" (click)="ShowDropDown()"  /&gt;
  
  &lt;div #tref *ngIf="showDropDown == 1" class="dropdownList" (focusout)="HideDropDown()" style="border:1px solid black;" &gt;this is my test&lt;/div&gt;
  </code></pre>
  
  <p>After clicking  the dropDownContainer i would like the dropdownList to appear and have focus put on it. </p>
  
  <p>I Have tried using </p>
  
  <pre><code>  @ViewChild("tref", {read: ElementRef}) tref: ElementRef; 
  </code></pre>
  
  <p>method, but it returns undefined because that element doesnt exist in the DOM until the above <code>div</code> is clicked. How can I autofocus on a dynamic <em>NON INPUT</em> DOM object?</p>
  
  <p><strong><em>EDIT</em></strong> Updated my code per suggestions, this still will not autofocus on the div.</p>
  
  <pre><code>  @ViewChild("tref") tref: ElementRef;
        ShowDropDown() {
        this.showDropDown = 1;
        this.tref.nativeElement.focus();
        console.log(this.tref);
    }
  HideDropDown(){
    console.log('test out')
    this.showDropDown = 0;
  }
  
  
  
  &lt;input   #tref class="dropdownContainer" placeholder="george" (click)="ShowDropDown()"  /&gt;
  &lt;div tabindex="-1" (focusout)="HideDropDown()" [hidden]="showDropDown == 0" class="dropdownList"  style="border:1px solid black;" &gt;this is my test&lt;/div&gt;
  </code></pre>
  
  <p><strong><em>ANSWER TO THE PROBLEM</em></strong>
  Two fold answer.</p>
  
  <p>1) DIVS cannot have focus unless they have tabindex. <a href="https://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus">Stack answer </a></p>
  
  <p>2)I need to include <code>setTimeout(() =&gt; this.tref.nativeElement.focus(), 1);</code> because an element that is <code>hidden</code> is not automatically ready to receive focus.</p>
  
  <p>3)*ngIf and hidden both worked, once i put in the above fixes</p>
  
  <p>Cleaned up code</p>
  
  <pre><code>import { Component,  ElementRef , ViewChild } from '@angular/core';
  
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.less']
  })
  export class AppComponent {
  
    constructor() {
    }
  
    showDropDown = 0;
  
  
  
    @ViewChild("tref") tref: ElementRef;
    ShowDropDown() {
  this.showDropDown = 1;
  setTimeout(() =&gt; this.tref.nativeElement.focus(), 1);
    }
  
  HideDropDown(){
    this.showDropDown = 0;
  }
  
  test(){ console.log('works');}
  
  }
  
  &lt;div tabindex="-2"    class="dropdownContainer" placeholder="george" (click)="ShowDropDown()"   &gt;&lt;/div&gt;
  &lt;div tabindex="-1" #tref [hidden]="showDropDown == 0" class="dropdownList"  style="border:1px solid black;" (click)="test()" (focusout)="HideDropDown()"&gt;this is my test&lt;/div&gt;
  </code></pre>