ViewChild and ViewChildren

Parekh Dharmesh T
2 min readJul 29, 2021

This blog is in a continuation of my previous blog (Angular Component Communication). This blog will focus further on communication between component and template.

We all know (whoever used JavaScript or JQuery) how html element reference can be obtained in JavaScript and JQuery.

Obtain reference of Html Element using JavaScript and JQuery

Our angular component can also obtain reference of html element or directive. There are two decorators named ViewChild and ViewChildren in angular through which we can get the reference of html element or elements.

@ViewChild

Sometimes component (.ts) might need reference of single or multiple html elements and these html elements are part of template. Once component obtain reference of html element then component can change/read property value and execute method (setting focus to input element by calling .focus method).This is where we can use ViewChild decorator.

When is variable injected via @ViewChild available?

It will not be available immediately after component construction and initialization. It will be available only after view initialization is complete. look at below angular component life cycle hook or events.

Life cycle hooks with reference to View Initialization
Life cycle events or hooks with reference to @ViewChild decorator

Let us take one example — Your component wants to set focus on input html element.

  1. Specify template variable in HTML element
  2. Implement AfterViewInit in your component
  3. Define ViewChild decorator to get the reference of html element
  4. Change/Read property value or execute element method

--

--