View Child And View Children In Angular

We will discuss View Child and View Children decorators in angular with practical implementation with the help of angular.

Overview

  • Suppose we want to access DOM elements present inside the HTML Template of the same or child component. In that case, we can use View Child and View Children Decorators.
  • Also, if we want to access child component properties and methods, that is possible by using View Child and View Children Decorators.

Implementation

Child component HTML File

<div class="alert alert-secondary" role="alert" style="padding: 30px;margin: 40px;">
    <h3 #childheading>Child Component</h3>
</div>
  • As we can see, we have a heading element and a reference variable with hash and name as a child heading.
  • Suppose we want to access this heading DOM element for that need to use View Child decorator inside the child component type script file, as shown below.

Child Component TypeScript file

import {
    Component,
    ElementRef,
    Renderer2,
    ViewChild
} from '@angular/core';
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    //View Child
    @ViewChild("childheading") childheading!: ElementRef;
    constructor(private renderer: Renderer2) {}
    ngOnInit(): void {}
    ngAfterViewInit(): void {
        console.log(this.childheading)
        //ViewChild
        this.renderer.setStyle(this.childheading.nativeElement, 'background-color', 'red');
    }
}
  • Line 1 - Import ViewChild, ElementRef, and Renderer2 from the angular core library.
  • Line 10 - Create ViewChild element, a type of ElementRef, and put reference variable inside ViewChild in double quote.
  • Line 12 - Inject Renderer2 inside the constructor, which we will use to change the properties of the DOM element.
  • After that, use the ngAfterViewInit angular lifecycle hook to access the HTML DOM element when that gets rendered and initialized.
  • Line 21 - console logs the child heading to see details about that property inside inspect section in the browser.

View Child and View Children in Angular

  • Here inside the console section, we can see ElementRef and native element when we run our application, and there are many properties you can access and change, as I showed below.
  • Line 24 -Set different styles to a native element using renderers like font, background color, and many more.

Suppose we want to access another heading with the same reference variable as a child heading; that is not possible using View Child. We need to use View Children because View Child only points to the first matching DOM reference element.

Let’s start the implementation of View Children,

Child Component HTML File

<div class="alert alert-secondary" role="alert" style="padding: 30px;margin: 40px;">
    <h3 #childheading>Child Component</h3>
    <h3 #childheading> Demo </h3>
</div>
  • Here we can see now have two headings with the same template reference variable, and using View Children; we will set different properties for each of them.

Child Component TypeScript file

import {
    Component,
    QueryList,
    Renderer2,
    ViewChildren
} from '@angular/core';
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    //View Children
    @ViewChildren("childheading") childheading!: QueryList < any > ;
    constructor(private renderer: Renderer2) {}
    ngOnInit(): void {}
    ngAfterViewInit(): void {
        console.log(this.childheading)
        //ViewChildren
        this.renderer.setStyle(this.childheading.first.nativeElement, 'color', 'red');
        this.renderer.setStyle(this.childheading.last.nativeElement, 'color', 'blue');
    }
}
  • Line 1 - Import QueryList, Renderer2, and ViewChildren from the angular core library.
  • Line 10 - Create a ViewChildren object, a type of QueryList<any>, and put a template reference variable inside that.
  • Line 12 - Inject Renderer2 inside the constructor
  • Line 20 - Use ngAfterViewInit Angular lifecycle hook, which will get triggered when elements are initialized.
  • Line 21 - The console logs the child heading; we can see details about that when we run the application.

View Child and View Children in Angular

Here you can see the query list with two native element details first and last.

  • Line 24:25 - Set different styles or anything based on the property to the first and last element.

This is about accessing the DOM elements using ViewChild and View Children.

Now we will access the child component method into the parent component by using the View Child decorator.

Child Component HTML file

<div class="alert alert-secondary" role="alert" style="padding: 30px;margin: 40px;">
    <h3>Child Component</h3>
    <h5>{{message}}</h5>
</div>

As you can see, we use string interpolation to display the message when the method is executed.

Child Component TypeScript file

import {
    Component
} from '@angular/core';
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    message: string = "";
    constructor() {}
    ngOnInit(): void {}
    //Child Method
    childMethod() {
        this.message = 'Hi, Parent Component Invoke Child Method...';
    }
}

Inside the child component, declare one message property and one child method that just put some string message inside our property, and now we will execute this child method from the parent component.

Parent Component TypeScript File

import {
    Component,
    ViewChild
} from '@angular/core';
import {
    ChildComponent
} from './child/child.component';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'viewchildandchildrendemo';
    @ViewChild("childMethod") method!: ChildComponent
    parentFunction() {
        this.method.childMethod();
    }
}
  • Here we create a View Child object, a type of child component, and put the method name we want to access.
  • After that, create one parent function and invoke the child component method inside that.

Parent Component HTML File

<nav class="navbar navbar-light bg-light" style="padding: 30px;margin: 40px; justify-content:center">
  <span class="navbar-brand mb-0 h1">Angular Component Communication</span>
</nav>

<div class="alert alert-primary" role="alert" style="padding: 30px;margin: 40px;">
  <h3>Parent Component</h3>
  <button (click) = "parentFunction()">Call child component method</button>
</div>

<app-child #childMethod></app-child>
  • We call the child component inside the HTML file using the angular selector and child method reference variable.
  • Also, create one button using event binding and call the parent function pointing to the child method.

View Child and View Children in Angular

So, this is all about View Child and View Children.

GitHub Link

https://github.com/Jaydeep-007/ViewChildAndChildrenDemo

Happy Coding!


Similar Articles