AngularJS 2.0 From Beginning - ViewChild - Day Nine

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss ViewChild in AngularJS 2. Also, in case you did not have a look at the previous articles of this series, go through the links mentioned below.

In my previous article, I already discussed about Pipes in Angular 2.0. In that article, we discussed about the Angular 2.0 predefined pipes and also discussed how to create custom pipes`. Now in this article, I will discuss about ViewChild.

Basically, ViewChild is one of the new features introduced in Angular 2.0 framework. Since Angular 2.0 basically depends on component architecture, when we try to develop any web page or UI, it is most obvious that the page or UI must be a component, which basically contains a number of multiple different types of components within that component. In simple words, it is basically a parent component – child component based architecture. In this scenario, there are some situations when a parent component needs to interact with the child component. There are multiple ways to achieve this interaction between parent and child component. One of the ways is ViewChild. So when a parent component needs to execute or call any method of the child component, it can inject child component as a ViewChild within the parent component.

  1. @ViewChild('calculator') private _calculator: ChildComponent;  
For implementing ViewChild, we need to use @ViewChild decorator in the parent component. The @ViewChild decorator provides access to the class of child component from the parent component. The @ViewChild is a decorator function that takes the name of a component class as its input and finds its selector in the template of the containing component to bind to. @ViewChild can also be passed a template reference variable.

Now, for illustrating this, we will develop a calculator type UI. In this, we will develop two components. 

  • First component i.e. child component contains two textboxes from taking inputs and four buttons for performing four basic mathematical operations. After completion of the operations, each button will emit its final value to the parent component so that the parent component can show those values or perform any other operations on the basis of those value.
  • Now, parent component wants to clear the values from both its own component and also from child component. For clearing the child component value, parent component will access the child component’s clear() by using the @ViewChild decorator.

Now, to illustrate the ViewChild, follow the below lab exercise.

Step 1 

First, create an html file named app.component.child.html and add the below code.
  1. <div class="ibox-content">  
  2.     <div class="row">  
  3.         <div class="col-md-4">  
  4.             Enter First Number  
  5.         </div>  
  6.         <div class="col-md-8">  
  7.             <input type="number" [(ngModel)]="firstNumber" />  
  8.         </div>  
  9.     </div>  
  10.     <div class="row">  
  11.         <div class="col-md-4">  
  12.             Enter Second Number  
  13.         </div>  
  14.         <div class="col-md-8">  
  15.             <input type="number"  [(ngModel)]="secondNumber" />  
  16.         </div>  
  17.     </div>  
  18.     <div class="row">  
  19.         <div class="col-md-4">  
  20.         </div>  
  21.         <div class="col-md-8">  
  22.            <input type="button" value="+" (click)="add()" />  
  23.                 
  24.             <input type="button" value="-" (click)="subtract()" />  
  25.                 
  26.             <input type="button" value="X" (click)="multiply()" />  
  27.                 
  28.             <input type="button" value="/" (click)="divide()" />  
  29.         </div>  
  30.     </div>  
  31. </div> 
Step 2 

Now, create a TypeScript file named app.component.child.ts and add the below code.
  1. import { Component, OnInit, Output, EventEmitter } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'child',  
  6.     templateUrl: 'app.component.child.html'  
  7. })  
  8.   
  9. export class ChildComponent implements OnInit {  
  10.     private firstNumber: number = 0;  
  11.     private secondNumber: number = 0;  
  12.     private result: number = 0;  
  13.   
  14.     @Output() private addNumber: EventEmitter<number> = new EventEmitter<number>();  
  15.     @Output() private subtractNumber: EventEmitter<number> = new EventEmitter<number>();  
  16.     @Output() private multiplyNumber: EventEmitter<number> = new EventEmitter<number>();  
  17.     @Output() private divideNumber: EventEmitter<number> = new EventEmitter<number>();  
  18.   
  19.     constructor() { }  
  20.   
  21.     ngOnInit(): void {  
  22.     }  
  23.   
  24.     private add(): void {  
  25.         thisthis.result = this.firstNumber + this.secondNumber;  
  26.         this.addNumber.emit(this.result);  
  27.     }  
  28.   
  29.     private subtract(): void {  
  30.         thisthis.result = this.firstNumber - this.secondNumber;  
  31.         this.subtractNumber.emit(this.result);  
  32.     }  
  33.   
  34.     private multiply(): void {  
  35.         thisthis.result = this.firstNumber * this.secondNumber;  
  36.         this.multiplyNumber.emit(this.result);  
  37.     }  
  38.   
  39.     private divide(): void {  
  40.         thisthis.result = this.firstNumber / this.secondNumber;  
  41.         this.divideNumber.emit(this.result);  
  42.     }  
  43.   
  44.     public clear(): void {  
  45.         this.firstNumber = 0;  
  46.         this.secondNumber = 0;  
  47.         this.result = 0;  
  48.     }  

Step 3

Add another html file named app.component.parent.html files and add the below code.
  1. <div>  
  2.     <h2>Simple Calculator</h2>  
  3.     <div>  
  4.         <child (addNumber)="add($event)" (subtractNumber)="subtract($event)" (multiplyNumber)="multiply($event)"  
  5.                 (divideNumber)="divide($event)" #calculator></child>  
  6.     </div>  
  7.     <h3>Result</h3>  
  8.     <span>{{result}}</span>  
  9.     <br />  
  10.     <br />  
  11.     <input type="button" value="Reset" (click)="reset()" />  
  12. </div> 
Step 4

Add another TS file named app.component.parent.ts and add the below code.
  1. import { Component, OnInit, ViewChild } from '@angular/core';  
  2. import { ChildComponent } from './app.component.child';  
  3.   
  4. @Component({  
  5.     moduleId: module.id,  
  6.     selector: 'parent',  
  7.     templateUrl: 'app.component.parent.html'  
  8. })  
  9.   
  10. export class ParentComponent implements OnInit {  
  11.     private result: string = '';  
  12.   
  13.     @ViewChild('calculator') private _calculator: ChildComponent;  
  14.   
  15.     constructor() {  
  16.     }  
  17.   
  18.     ngOnInit(): void {  
  19.     }  
  20.   
  21.     private add(value: number): void {  
  22.         this.result = 'Result of Addition ' + value;  
  23.     }  
  24.   
  25.     private subtract(value: number): void {  
  26.         this.result = 'Result of Substraction ' + value;  
  27.     }  
  28.   
  29.     private multiply(value: number): void {  
  30.         this.result = 'Result of Multiply ' + value;  
  31.     }  
  32.   
  33.     private divide(value: number): void {  
  34.         this.result = 'Result of Division ' + value;  
  35.     }  
  36.   
  37.     private reset(): void {  
  38.         this.result = '';  
  39.         this._calculator.clear();  
  40.     }  

Step 5

Now, add app.module.ts file and write down the below code.
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { FormsModule } from "@angular/forms";  
  4. import { ParentComponent } from './src/app.component.parent';  
  5. import { ChildComponent } from './src/app.component.child';  
  6.   
  7. @NgModule({  
  8.     imports: [BrowserModule, FormsModule],  
  9.     declarations: [ParentComponent, ChildComponent],  
  10.     bootstrap: [ParentComponent]  
  11. })  
  12. export class AppModule { } 
Step 6

Now, add main.ts file and write down the below code.
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule); 
Step 7

Now, add the index.html file and write down the below code.
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Angular2 - ViewChild</title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link href="../resources/style/style1.css" rel="stylesheet" />  
  8.     <!-- Polyfill(s) for older browsers -->  
  9.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  10.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  11.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  12.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  13.     <script src="../systemjs.config.js"></script>  
  14.     <script>  
  15.         System.import('app').catch(function (err) { console.error(err); });  
  16.     </script>  
  17. </head>  
  18. <body>  
  19.     <parent>Loading</parent>  
  20.       
  21. </body>  
  22. </html> 
Run the index.html file in browser and see the output.


Similar Articles