Angular 9/8 DOM Queries: ViewChild and ViewChildren Example

Angular 9/8 DOM Queries: ViewChild and ViewChildren Example

The @ViewChild and @ViewChildren decorators in Angular provide a way to access and manipulate DOM elements, directives and components. In this tutorial, we'll see an Angular 9 example of how to use the two decorators.

You can use ViewChild if you need to query one element from the DOM and ViewChildren for multiple elements.

We'll be using an online development IDE available from https://stackblitz.com/ so you don't need to set up your local development machine for Angular at this point.

Head over to Stackblitz, sign in with your GitHub account and choose an Angular workspace:

Angular Stackblitz

You should be presented with an online IDE with an Angular 8 project:

Angular 9 ViewChild Example

ViewChild and ViewChildren Angular 9 Example

Our Angular 9 project contains the usual App component and a child component called HelloComponent and defined in the src/app/hello.component.ts file with the followign code:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello !</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
}

The component accepts a name property and uses an inline template which simply displays the value passed via the name property from the parent component.

In the component decorator, we used hello as the selector for the component so in the the HTML template of the App component defined in the src/app/app.component.html file, we include the child component using the following code:

<hello name=""></hello>
<p>
  Start editing to see some magic happen :)
</p>

After running our Angular application the hello component is rendered and becomes part of the DOM so we can query it just like any normal DOM element.

What's ViewChild in Angular?

ViewChild is a decorator that creates a view or DOM query. According to the docs

Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

The decorator takes the following meta information:

  • selector - the selector of the element to query. This can be a directive type or a name.
  • read - read a different token from the queried elements.
  • static - This is new in Angular 8 and indicates whether or not to resolve query results before change detection runs.

ViewChild can take the following selectors:

  • Classes with the @Component or @Directive decorators i.e components and directives,
  • Template reference variables,
  • Providers,
  • TemplateRef

Now, let's go back to our src/app/app.component.ts file and let's see how we can query the child component using ViewChild. First, change the code accordingly:

import { Component, ViewChild, AfterViewInit } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

  ngAfterViewInit() {
    console.log('Hello ', this.hello.name); 
  }
}

In the console, you should get Hello Angular:

Angular 9 ViewChild

Now, let's explain the code.

First, we imported HelloComponent and ViewChild and AfterViewInit from the @angular/core package:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { HelloComponent } from './hello.component';

Next, we create a query called hello that takes HelloComponent as the selector and has static equals to false:

@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

In Angular 9, timing for ContentChild and ViewChild needs to be specified explicitly.

See: ​Why do I have to specify {static: false}? Isn't that the default?

Next, in the ngAfterViewInit() life-cycle hook, we can use the query to access the DOM element for the hello component. In our example, we accessed the name property of the component, after it's mounted in the DOM, which contains the Angular string:

  ngAfterViewInit() {
    console.log('Hello ', this.hello.name); 
  }

We can access any properties and even methods from the queried component.

Note: View queries are set before the ngAfterViewInit callback is called.

Querying Standard HTML Elements with Angular Template References

We can also query standard HTML elements using ViewChild and template reference variables. Let's go back to our src/app/app.component.html file and change it as follows:

<hello name=""></hello>

<p #pRef>
  Start editing to see some magic happen :)
</p>

We simply added the helloRef template reference to our hello component. Now let's change our code to access the component using its reference. Go back to the src/app/app.component.ts file and change accordingly:

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

  @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML); 
    this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; 
  }
}

We import ElementRef and we create a query configuration to access the <p> DOM element with the #pRef template reference as follows:

  @ViewChild('pRef', {static: false}) pRef: ElementRef;

Next, in the ngAfterViewInit() method we can access and modify the native DOM element using the nativeElement object of ElementRef:

  @ViewChild('pRef', {static: false}) pRef: ElementRef;

    ngAfterViewInit() {
    console.log(this.pRef.nativeElement.innerHTML);
    this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; 
  }

Angular 9 ViewChild

This is the live example from this link.

What's ViewChildren in Angular?

ViewChildren is another property decorator which is used to query the DOM for multiple elements and return a QueryList.

According to the docs:

You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.

Angular 9 ViewChildren by Example

Let's see an example.

Go to the src/app/app.component.html file and update it as follows:

<hello  name="Angular 6"  ></hello>
<hello  name="Angular 7"  ></hello>
<hello  name="Angular 8"  ></hello>
<hello  name="Angular 9"  ></hello>

We are simply displaying the hello component three times. Let's now query the DOM. Open the src/app/app.component.ts file and change it as follows:

import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';

import { HelloComponent } from './hello.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';
  @ViewChildren(HelloComponent) hellos: QueryList<any>;

  ngAfterViewInit() {

     this.hellos.forEach(hello => console.log(hello));

  }
}

You should this output in the console:

Angular 9 ViewChildren Example

Now, let's explain the code.

First we import ViewChildren, AfterViewInit and QueryList from @angular/core package.

Next, we create a vquery configuration for accessing multiple DOM elements:

@ViewChildren(HelloComponent) hellos: QueryList<any>;

@ViewChildren returns a QueryList which stores a list of items. When the state changes Angular will automatically update this query list.

Finally, in the ngAfterViewInit() method, we can iterate over the query list and log each DOM element:

  ngAfterViewInit() {
     this.hellos.forEach(hello => console.log(hello));
  }

You can find the live example from this link.

Conclusions

In this tutorial, we've seen how we can access and modify the DOM in Angular 9 using ViewChild and ViewChildren decorators and a couple of other APIs like QueryList and ngAfterViewInit()



Angular 9 Components: Input and Output
Angular 13 selectors
Picture-in-Picture with JavaScript and Angular 10
Jasmine Unit Testing for Angular 12
Angular 9 Tutorial By Example: REST CRUD APIs & HTTP GET Requests with HttpClient
Angular 10/9 Elements Tutorial by Example: Building Web Components
Angular 10/9 Router Tutorial: Learn Routing & Navigation by Example
Angular 10/9 Router CanActivate Guards and UrlTree Parsed Routes
Angular 10/9 JWT Authentication Tutorial with Example
Style Angular 10/9 Components with CSS and ngStyle/ngClass Directives
Upload Images In TypeScript/Node & Angular 9/Ionic 5: Working with Imports, Decorators, Async/Await and FormData
Angular 9/Ionic 5 Chat App: Unsubscribe from RxJS Subjects, OnDestroy/OnInit and ChangeDetectorRef
Adding UI Guards, Auto-Scrolling, Auth State, Typing Indicators and File Attachments with FileReader to your Angular 9/Ionic 5 Chat App
Private Chat Rooms in Angular 9/Ionic 5: Working with TypeScript Strings, Arrays, Promises, and RxJS Behavior/Replay Subjects
Building a Chat App with TypeScript/Node.js, Ionic 5/Angular 9 & PubNub/Chatkit
Chat Read Cursors with Angular 9/Ionic 5 Chat App: Working with TypeScript Variables/Methods & Textarea Keydown/Focusin Events
Add JWT REST API Authentication to Your Node.js/TypeScript Backend with TypeORM and SQLite3 Database
Building Chat App Frontend UI with JWT Auth Using Ionic 5/Angular 9
Install Angular 10 CLI with NPM and Create a New Example App with Routing
Styling An Angular 10 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards
Integrate Bootstrap 4/jQuery with Angular 10 and Styling the UI With Navbar and Table CSS Classes
Angular 10/9 Tutorial and Example: Build your First Angular App
Angular 9/8 ngIf Tutorial & Example
Angular 10 New Features
Create New Angular 9 Workspace and Application: Using Build and Serve
Angular 10 Release Date: Angular 10 Will Focus on Ivy Artifacts and Libraries Support
HTML5 Download Attribute with TypeScript and Angular 9
Angular 9.1+ Local Direction Query API: getLocaleDirection Example
Angular 9.1 displayBlock CLI Component Generator Option by Example
Angular 9 Basics Tutorial by Example
Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example
Responsive Image Breakpoints Example with CDK's BreakpointObserver in Angular 9/8
Angular 9/8 DOM Queries: ViewChild and ViewChildren Example
The Angular 9/8 Router: Route Parameters with Snapshot and ParamMap by Example
Angular 9/8 Nested Routing and Child Routes by Example
Angular 9 Examples: 2 Ways To Display A Component (Selector & Router)
Angular 9/8 Tutorial: Http POST to Node/Express.js Example
Angular 9/8 Feature and Root Modules by Example
Angular 9/8 with PHP: Consuming a RESTful CRUD API with HttpClient and Forms
Angular 9/8 with PHP and MySQL Database: REST CRUD Example & Tutorial
Unit Testing Angular 9/8 Apps Tutorial with Jasmine & Karma by Example
Angular 9 Web Components: Custom Elements & Shadow DOM
Angular 9 Renderer2 with Directives Tutorial by Example
Build Progressive Web Apps (PWA) with Angular 9/8 Tutorial and Example
Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example
Create Angular 9 Calendar with ngx-bootstrap datepicker Example and Tutorial
Multiple File Upload with Angular 9 FormData and PHP by Example
Angular 9/8 Reactive Forms with Validation Tutorial by Example
Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)
Angular 9/8 JAMStack By Example
Angular HttpClient v9/8 — Building a Service for Sending API Calls and Fetching Data
Build an Angular 9/8 CRUD Example & Tutorial
Styling An Angular 9/8/7 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards
Angular 8/7 Tutorial By Example: (REST API, HttpClient GET, Components, Services & ngFor)

✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!