Search code examples
angularviewchild

Element reference of ViewChild is undefined


Take a look at code below.

// ...

  @ViewChild('searchBar', {static: false}) searchBar: IonSearchbar;
  @ViewChild('locations', {static: false}) locationsList: IonList;

// ...

  ngAfterViewInit() {
    this.searchBarInputSub =
      this.searchBar.ionInput
        .pipe(
          pluck('target', 'value'),
          debounceTime(400),
          distinctUntilChanged()
        ).subscribe(this.onNewLocation);
    console.log(this.locationsList);
  }

  onNewLocation(prefix: string) {
    console.log(this.locationsList);
  }

Why onNewLocation prints undefined? Note that ngAfterViewInit prints an object description...


Solution

  • The syntax is incorrect when you subscribe to the observable, also the this in the line subscribe(this.onNewLocation) is not referring to what you think it is.

    Make the following change:

    ngAfterViewInit() {
       this.searchBarInputSub =
          this.searchBar.ionInput
            .pipe(
              pluck('target', 'value'),
              debounceTime(400),
              distinctUntilChanged()
            )
            .subscribe((location: string) => this.onNewLocation(location));
      }