Search code examples
htmlangular

Angular - How to access input element by ID within @if statements?


I'm trying to build a search bar. Depending on a condition, I want to display a different input element with a directive. The problem that I'm having is getting my button element to recognize the input element of the search bar. I get the following error: NG1: Property 'searchBar' does not exist on type '...'.. Anyone know what I'm doing wrong?

@if(condition){
  <input
    #searchBar
    some-directive 
  >
}
@else {
  <input
    #searchBar
  >
}

<button (click)="onSearch(searchBar.value)">Search</button>

Solution

  • variable scope related issue. workaround: define a variable in your ts file like this

      @ViewChild('searchBar') searchBar!: ElementRef<HTMLInputElement>;
    

    in html file:

    <button (click)="onSearch(searchBar.nativeElement.value)">Search</button>