Loading...

ViewChild() in Angular

ViewChild() is a decorator in Angular that allows you to access a child component, directive, or DOM element from a parent component's class. It provides a way to interact with elements defined in the template from the component's TypeScript code.

ViewChild() allows you to query the template for the first element that matches a given selector. This selector can be a component, directive, or template reference variable.

Why Use ViewChild()?

  • Component Interaction: Allows you to call methods and access properties of child components.
  • Directive Interaction: Enables you to interact with directives applied to elements.
  • DOM Manipulation: Facilitates direct manipulation of DOM elements.

Using ViewChild()

To use ViewChild(), you need to import it from @angular/core and use it as a decorator on a property in your component class.

Example 1: Accessing a Child Component

In this example, we'll access a child component and call its method.

Child Component (child.component.ts)


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

    @Component({
      selector: 'app-child',
      template: '<p>Child Component</p>'
    })
    export class ChildComponent {
      showMessage(): void {
        alert('Hello from ChildComponent!');
      }
    }
    

Parent Component (parent.component.ts)


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

    @Component({
      selector: 'app-parent',
      template: '<app-child></app-child><button (click)="callChildMethod()">Call Child Method</button>'
    })
    export class ParentComponent implements AfterViewInit {
      @ViewChild(ChildComponent) childComponent: ChildComponent;

      ngAfterViewInit(): void {
        console.log('Child Component:', this.childComponent);
      }

      callChildMethod(): void {
        this.childComponent.showMessage();
      }
    }
    

Explanation:

  • @ViewChild(ChildComponent) childComponent: ChildComponent;: Decorates the childComponent property with ViewChild(), specifying the ChildComponent as the selector.
  • ngAfterViewInit(): Lifecycle hook that runs after the component's view has been initialized.
  • callChildMethod(): Calls the showMessage() method of the ChildComponent instance.

Example 2: Accessing a Directive

In this example, we'll access a directive and use its properties.

Directive (highlight.directive.ts)


    import { Directive, ElementRef, HostListener } from '@angular/core';

    @Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective {
      constructor(private el: ElementRef) {}

      @HostListener('mouseenter') onMouseEnter() {
        this.highlight('yellow');
      }

      @HostListener('mouseleave') onMouseLeave() {
        this.highlight(null);
      }

      private highlight(color: string) {
        this.el.nativeElement.style.backgroundColor = color;
      }
    }
    

Parent Component (parent.component.ts)


    import { Component, ViewChild, AfterViewInit } from '@angular/core';
    import { HighlightDirective } from './highlight.directive';

    @Component({
      selector: 'app-parent',
      template: '<p appHighlight>Highlight me!</p><button (click)="changeHighlight()">Change Highlight</button>'
    })
    export class ParentComponent implements AfterViewInit {
      @ViewChild(HighlightDirective) highlightDirective: HighlightDirective;

      ngAfterViewInit(): void {
        console.log('Highlight Directive:', this.highlightDirective);
      }

      changeHighlight(): void {
        this.highlightDirective['highlight']('lightblue');
      }
    }
    

Explanation:

  • @ViewChild(HighlightDirective) highlightDirective: HighlightDirective;: Decorates the highlightDirective property with ViewChild(), specifying the HighlightDirective as the selector.
  • ngAfterViewInit(): Lifecycle hook that runs after the component's view has been initialized.
  • changeHighlight(): Calls the highlight() method of the HighlightDirective instance.

Example 3: Accessing a DOM Element

In this example, we'll access a DOM element using a template reference variable.

Parent Component (parent.component.ts)


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

    @Component({
      selector: 'app-parent',
      template: '<input type="text" #myInput><button (click)="focusInput()">Focus Input</button>'
    })
    export class ParentComponent implements AfterViewInit {
      @ViewChild('myInput') myInput: ElementRef;

      ngAfterViewInit(): void {
        console.log('Input Element:', this.myInput);
      }

      focusInput(): void {
        this.myInput.nativeElement.focus();
      }
    }
    

Explanation:

  • @ViewChild('myInput') myInput: ElementRef;: Decorates the myInput property with ViewChild(), specifying 'myInput' (the template reference variable) as the selector.
  • ngAfterViewInit(): Lifecycle hook that runs after the component's view has been initialized.
  • focusInput(): Calls the focus() method on the native element of the input.

Key Points

  • ViewChild() allows access to child components, directives, and DOM elements.
  • Use it in combination with the AfterViewInit lifecycle hook.
  • It simplifies interactions with elements defined in the template.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!