Categories
Angular Answers

How to fix @ViewChild annotation returns undefined with Angular?

Spread the love

Sometimes, we want to fix @ViewChild annotation returns undefined with Angular.

In this article, we’ll look at how to fix @ViewChild annotation returns undefined with Angular.

How to fix @ViewChild annotation returns undefined with Angular?

To fix @ViewChild annotation returns undefined with Angular, we can watch the @ViewChild for changes.

For instance, we write

import {
  Component,
  ViewChildren,
  OnInit,
  AfterViewInit,
  QueryList,
} from "@angular/core";
import { GridComponent } from "@progress/kendo-angular-grid";

export class SearchComponent implements OnInit, AfterViewInit {
  //...
  @ViewChildren("searchGrid")
  public Grids: QueryList<GridComponent>;

  private SearchGrid: GridComponent;

  public ngAfterViewInit(): void {
    this.Grids.changes.subscribe((comps: QueryList<GridComponent>) => {
      this.SearchGrid = comps.first;
    });
  }
}

to call this.Grids.changes.subscribe in ngAfterViewInit to watch for changes in the Grids @ViewChild variable.

We call it with a callback that gets the element nodes QueryList list value.

And we get the element from comps.first when it changes.

Conclusion

To fix @ViewChild annotation returns undefined with Angular, we can watch the @ViewChild for changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *