Angular 2 Parent - Child interaction using ViewChild


Example

Viewchild offers one way interaction from parent to child. There is no feedback or output from child when ViewChild is used.

We have a DataListComponent that shows some information. DataListComponent has PagerComponent as it's child. When user makes a search on DataListComponent, it gets a data from a service and ask PagerComponent to refresh paging layout based on new number of pages.

import { Component, NgModule, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataListService } from './dataList.service';
import { PagerComponent } from './pager.component';

@Component({
    selector: 'datalist',
    template: `<input type='text' [(ngModel)]="searchText" />
               <button (click)="getData()">Search</button>
        <table>
        <tr *ngFor="let person of personsData">
            <td>{{person.name}}</td>
            <td>{{person.surname}}</td>
        </tr> 
        </table>

        <pager></pager>
    `
})
export class DataListComponent {
    private personsData = null;
    private searchText: string;

    @ViewChild(PagerComponent)
    private pagerComponent: PagerComponent;

    constructor(private dataListService: DataListService) {}
    
    getData(){
        var response = this.dataListService.getData(this.searchText);
        this.personsData = response.data;
        this.pagerComponent.setPaging(this.personsData / 10); //Show 10 records per page
    }
}

@NgModule({
    imports: [CommonModule],
    exports: [],
    declarations: [DataListComponent, PagerComponent],
    providers: [DataListService],
})
export class DataListModule { }

In this way you can call functions defined at child components.

Child component is not available until parent component is rendered. Attempting to access to the child before parents AfterViewInit life cyle hook will cause exception.