0

My template

    @ViewChildren('search') searchInput: QueryList<any>;

    toggleSearch(){
        this.showSearch = !this.showSearch;
        if (this.showSearch){
            console.log(this.searchInput.first); <= undefined
        }
    }
   <li class="search" *ngIf="showSearch" >
    <i class="news-admin-icon news-admin-search"></i>
    <input (blur)="toggleSearch()" #search (keyup)="searchNews(search.value)" type="text" placeholder="Search">
   </li>
   </li>
   <li class="special" *ngIf="!showSearch" (click)="toggleSearch(search)">
    <a href="#"><i class="news-admin-icon news-admin-search"></i>  Search</a>
   </li>

I Try get 'search' with @ViewChild but get undefined when I try get 'search' with @ViewChildren I get

QueryList_dirty: false_emitter: EventEmitter_results: Array[1]changes: (...)dirty: (...)first: (...)last: (...)length: (...)proto: Object

Green176
  • 349
  • 2
  • 3
  • 9

1 Answers1

0

Try adding this:

ngAfterViewChecked() {  // Called after child views changed
  if(this.showSearch && this.searchInput.first) {  // check is showSearch and ViewChildren has result
    this.searchInput.first.nativeElement.focus();  // set focus on native input element
  }
}
NagRock
  • 316
  • 4
  • 15