Angular 2+ :@view Child
ANGULAR2 @view Child
Viewchild offers one way interaction fro.m parent to child. There is no return mes.sage or output from child when ViewChild is used.
ViewChild is used for component to template communication. It is used to ref.erence a directive or element or component.
let element = document.getElementById('elementId');
@ViewChild('elementV.ariable') elementRef; // template reference variable
@ViewChild(NgModel) filterInput: NgModel; // angular
directive - on template would look like: <input
[(ngModel)]='listfilter'>
@ViewChild(Pare.ntComponent) Parent: (ParentComponent) // child com.ponent - on template would
look like: <child-component[input1]='some.input'>
We ha.ve
a DataListC.omponent that
shows som.e information.
DataListComponent has PagerComponent as it's child. When user. makes a search on
DataListComponent, it gets a data from a servic.e and ask PagerComponent torefresh paging .layout based on .new number of pages.
impo.rt
{ Component, NgModule, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataListService } from './dataList.service';
impo.rt
{ 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.dataL.istService.getData(this.searchText);
this.personsData =
response.data;
this.pagerCom.ponent.setPaging(this.personsData
/ 10); //Show 10 records per page
}
}
@NgModule({
imports:
[CommonModule],
exports: [],
declara.tions: [DataListComponent, Pag.erComponent], .
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.
Reference: https://goalkicker.com/
.
Contact Persons
Rajesh G
Software Developer At GGK
gundupallirajesh@gmail.com
Haswanth M
Front End Developer at TCS
haswanthmuktha@gmail.com
Poorna K
FullStack Dev at Wipro
poorna.k26@gmail.com
Comments
Post a Comment