Web
Analytics
angular 4 viewchild example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

  • ViewChild allows a one component to be injected into another.
  • This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.
  • ngAfterViewInit() is called after a component’s view, and its children’s views, are created. Its a lifecycle hook that is called after a component’s view has been fully initialized.

Step1: Create two components

ng g c myparent1 and ng g c mychild1

myparent1 Component

<p>
  myparent1 works!
</p>
<p>{{ message }}</p>
<app-mychild1></app-mychild1>
import { Component, OnInit , ViewChild ,AfterViewInit } from '@angular/core';
import { Mychild1Component } from '../mychild1/mychild1.component';

@Component({
  selector: 'app-myparent1',
  templateUrl: './myparent1.component.html',
  styleUrls: ['./myparent1.component.css']
})
export class Myparent1Component implements OnInit , AfterViewInit {

  @ViewChild(Mychild1Component) childdata;
  message: string;
  constructor() { }

  ngOnInit() {
  }
ngAfterViewInit()
{
  this.message = this.childdata.childvar;
}
}





mychild1component

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

@Component({
  selector: 'app-mychild1',
  templateUrl: './mychild1.component.html',
  styleUrls: ['./mychild1.component.css']
})
export class Mychild1Component implements OnInit {

  childvar: string ="This is child var data";
  constructor() { }

  ngOnInit() {
  }

}

Output

ViewChild Example output in angular 5