viewChild() vs ViewChildren() decorator

Introduction

When building Angular applications, interacting with child components, directives, or DOM elements is a common requirement. Angular provides two powerful decorators for this purpose: @ViewChild() and @ViewChildren(). Although they appear similar, they serve different purposes and understanding their differences is essential for writing clean, efficient, and maintainable Angular applications.

What are View Queries in Angular?

Angular uses view queries to access elements, directives, or child components that belong to a component’s own template.

There are two types of view queries:

  1. @ViewChild() – Retrieves the first matching element or component.
  2. @ViewChildren() – Retrieves all matching elements or components.

Note: These decorators allow developers to communicate directly with child components without relying on input/output bindings for every interaction.

What is @ViewChild()?

@ViewChild() is a property decorator that searches the component’s view and returns the first matching element, directive, or component.

It is commonly used when only one child component or DOM element needs to be accessed.

Syntax:


@ViewChild(selector, options?)
propertyName!: Type;

Parameter Explanations:

  • selector: Component class, template reference variable, or directive
  • options: Optional configuration such as static and read

Example: Call the Child Component method in the parent component using @ViewChild()

Suppose we have a child component.

child.component.ts


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

@Component({
 selector: 'app-child',
 template: `

Child Component

` }) export class ChildComponent { sayHello() { console.log('Hello from Child Component'); } }

Now access it from the parent component.

parent.component.html


<app-child></app-child>

<button (click)="callChild()">
   Call Child Method
</button>

parent.component.ts


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

import { ChildComponent } from './child.component';

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements AfterViewInit {

@ViewChild(ChildComponent)
child!: ChildComponent;

ngAfterViewInit() {
  console.log(this.child);
}

callChild() {
  this.child.sayHello();
}

}

Output:

Hello from Child Component

In the above example, the parent component directly calls the method defined inside the child component.

Example: Accessing HTML Elements with @ViewChild()

You can also access native HTML elements using template reference variables.

HTML:


<input #username />

<button (click)="focusInput()">
   Focus
</button>

TypeScript:


@ViewChild('username')
username!: ElementRef;

focusInput() {
 this.username.nativeElement.focus();
}

This is a common approach for focusing inputs, measuring element dimensions, or interacting with third-party libraries.

Example: Suppose you want to change the color of the  h1 tag through viewChild()

viewChild Example 1app.component.ts


import { AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })

  export class AppComponent  implements OnInit, AfterViewInit{

    @ViewChild('heading')  appHeading:ElementRef | undefined;
    constructor(){
    }
  
    ngOnInit() : void{
    }
    ngAfterViewInit(){
        if( this.appHeading){
          this.appHeading.nativeElement.style.color = "green";
        }
  }
}

app.component.html file


<div class="text-align-center col-sm-6" align="center">
<h1 #heading>App Component1</h1>
<h1 #heading>App Component2 </h1>
</div>

Now, you can see the output that only the first template reference variable color is changed.

viewChild Example 2

What is @ViewChildren()?

@ViewChildren() is another Angular decorator that returns all matching child elements or components as a QueryList.

Unlike @ViewChild(), which returns a single object, @ViewChildren() returns a collection.

Syntax


@ViewChildren(selector)
propertyName!: QueryList<Type>;

Example: Using @ViewChildren()

Suppose multiple child components exist.

parent.component.html


<app-child></app-child>
<app-child></app-child>
<app-child></app-child>

<button (click)="callAllChildren()">
   Call All
</button>

parent.component.ts


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

@ViewChildren(ChildComponent)
children!: QueryList;

callAllChildren() {
 this.children.forEach(child => {
     child.sayHello();
 });
}

Output:

Hello from Child Component
Hello from Child Component
Hello from Child Component

Every child component is accessed using the QueryList.

Example: manipulate the properties of the same template reference variable multiple times.

app.component.ts


import { AfterViewInit, Component, OnInit, QueryList, ViewChildren} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })

  export class AppComponent  implements OnInit, AfterViewInit{

    @ViewChildren('heading')  appHeading!: QueryList;
    constructor(){
    }
  
    ngOnInit() : void{
    }
    ngAfterViewInit(){
        if( this.appHeading){
          this.appHeading.first.nativeElement.style.color="green";
          this.appHeading.last.nativeElement.style.color="blue";
        }
  }
}

app.component.html file


<div class="text-align-center col-sm-6" align="center">
<h1 #heading>App Component1</h1>
<h1 #heading>App Component2 </h1>
</div>

Output: both template reference variable colors are changed.

viewChild Example 3

What is QueryList?

A QueryList is an Angular collection that stores all matched items returned by @ViewChildren().

ViewChild() vs ViewChildren()

Feature @ViewChild() @ViewChildren()
Returns Single object QueryList
Matches First matching element All matching elements
Suitable for One child Multiple children
Data Type Component or ElementRef QueryList
Supports Iteration No Yes
Common Use Form controls, single child Lists of components

Common Mistakes

Developers often make the following mistakes when working with view queries.

1. Using @ViewChild() for Multiple Components

Incorrect:


@ViewChild(ItemComponent)
item!: ItemComponent;

This returns only the first matching component.

Correct:


@ViewChildren(ItemComponent)
items!: QueryList;

2. Accessing Queries Too Early

Incorrect:


constructor() {
  console.log(this.child);
}

The view has not been initialized yet, so the query may be undefined.

Correct:


ngAfterViewInit() {
  console.log(this.child);
}

3. Forgetting to Use QueryList

Incorrect:


@ViewChildren(CardComponent)
cards!: CardComponent;

Correct:


@ViewChildren(CardComponent)
cards!: QueryList<CardComponent>;

4. Treating QueryList Like a Normal Array

A QueryList is not a standard JavaScript array. While it provides methods like forEach(), if you need full array functionality, convert it first:


const cardArray = this.cards.toArray();

5. Overusing ElementRef

Avoid excessive direct DOM manipulation:


this.element.nativeElement.style.color = 'red';

Prefer Angular bindings whenever possible:


<div [style.color]="textColor">

This approach is safer, easier to test, and works better with Angular’s rendering engine.

Angular viewChild() vs ViewChildren() – Interview Questions

Q 1: What is viewChild?
Ans: It retrieves a single child component or DOM element.
Q 2: What is ViewChildren?
Ans: It retrieves multiple child components or elements.
Q 3: When is viewChild resolved?
Ans: After component view initialization.
Q 4: What type does ViewChildren return?
Ans: QueryList.
Q 5: When should ViewChildren be used?
Ans: When accessing multiple child elements.

Angular viewChild() vs ViewChildren() – Objective Questions (MCQs)

Q1. ViewChild returns:






Q2. ViewChildren returns:






Q3. ViewChild is used for:






Q4. ViewChildren works with:






Q5. Both are used for:






Conclusion

@ViewChild() and @ViewChildren() are essential Angular decorators for querying child components, directives, and DOM elements within a component’s template.

The difference is: @ViewChild() retrieves the first matching item, while @ViewChildren() retrieves all matching items as a QueryList.

Related Angular viewChild() vs viewChildren() Tutorials