Sharing Data via ViewChild in Angular

In my last article we discuss on how to share data using Input & Output with event emitter.

Child to Parent Data Sharing via ViewChild

ViewChild decorator allows a one component injected in another component, it gives first(Parent) component access to its functions and class. Child component available after view initialized so we need ”


AfterViewInit” Life cycle hook for get data from child component.

Here is the sample example for passing data from child to parent using ViewChild decorator.
Parent Component Code


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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit   {
  
   @ViewChild(ChildComponent) child;

   message:string;

    ngAfterViewInit() {
      this.message = this.child.message
    }
  
}


  Message: {{ message }}

<app-child></app-child>


Child Component Code


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

@Component({
  selector: 'app-child',
  template: `
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message = 'Child Send Message';

  constructor() { }

}




Using @ViewChild to inject a reference to a DOM element
We can access native DOM elements using template reference variable. For example In our template with the Default Input value reference variable:


<input #nameInput placeholder="Enter Your Name">

In above example “nameInput” is template reference we can assign value using ViewChild.


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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  
   @ViewChild(ChildComponent) child;
   @ViewChild('nameInput') someInput: ElementRef;

   message:string;

    ngAfterViewInit() {
      this.message = this.child.message
      this.someInput.nativeElement.value = "Jugal";
    }
  
}

Full Embedded code For above codes.

Spread the love
  • 26
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •