Difference between viewChild() and ViewChildren() decorator

viewChild() Decorator:-1) we can manipulate the DOM through viewChild().
2) It manipulates the first matching element from the DOM.
like we can use only one time for same template reference variable.

viewChildren() Decorator:- 1) we can manipulate the DOM through viewChildren().
2) It manipulates the all matching element from the DOM.
like we can use multiple times (ElementRef) for same template reference variable.

Example:- Suppose, You want to change the color of the both h1 tag text.

ViewChild() Decorator provides a easy way to create and manipulate the properties and methods of a child component from a container or root component.

Step1) Now import ElementRef, ViewChild from ‘@angular/core’ in the app.component.ts file.


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";
        }
  }
}

Step2) Now add the below code into the 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>

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

ViewChildren() Decorator is used when we want to manipulate the properties of same template reference variable into multiple times.

Step1) Now import the QueryList, ViewChildren from ‘@angular/core’ and after that change the color of template reference variable through the property first and last.


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";
        }
  }
}

Step2) app.component.html file has same code as already defined above.

Step3) Now, you can see the output that both template reference variable colors are changed.