Inject child component in the parent component using the ViewChild decorator

Inject child component in the parent component using the ViewChild decorator


With the local template reference variable technique, only the parent template can access the property and methods of the child component, But the Instance of parent component class can not read/write child component properties and can not call the methods also.

To get access from the parent component class, we need to inject the child component as a view child. You can inject view child using the @ViewChild decorator.


Inject child component into Parent using @ViewChild



Child Component

user-input.component.ts 


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

@Component({
  selector: 'app-user-input',
  template:
    `
  {{timer}}
  
  `,
  styleUrls: ['./user-input.component.css']
})
export class UserInputComponent {

  timer = 100;
  myTimer : any;

  Startclock() {

    this.myTimer = setInterval(() => {
      
        this.timer--;

    }, 1000)
  }


  StopClock() {
    clearInterval(this.myTimer);
  }


}


The StartClock and StopClock are the methods of the child component. This component is only responsible to render a timer. To start or stop it, the parent component will call these methods.


Parent Component


import { Component, ViewChild } from '@angular/core';
import { UserInputComponent } from './user-input/user-input.component'

@Component({
  selector: 'app-root',
  template:
    `
<app-user-input></app-user-input>

<hr>
 
<button  type="button"  (click) = "start()"> Start </button> |
   
<button  type="button"  (click) = "stop()"> Stop </button>

  
  `
  ,
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  @ViewChild(UserInputComponent)
  private Child : UserInputComponent;
  

  start() {
    this.Child.Startclock();
  }

  stop() {
    this.Child.StopClock();
  }


}


Note: we have created a property named child which is decorated with the ViewChild of the child component and with the child property we can call our child components methods.


Angular ViewChild Example

Post a Comment

0 Comments