Explain the ViewChild and ViewChildren in Angular?

Anil Kumar
Dec 30, 2024

--

Photo by Pawel Czerwinski on Unsplash

View Child is Possibility to access Children components and children DOM elements. Some we don’t want to communicate using output and input either to directly call some method or change a value of child component or we want to access change in DOM element.

Parent Component

<child-component>
<button #button>

These are two way one is component and other is html element

  @ViewChild(ChildComponent, {static: true}) child?: ChildComponent
@ViewChild(‘’button’, {static: true}) buttonRef?: ElementRef<HTMLButtonElement>


ngAfterViewInit(){
this.child.property = 5;
}

in

In case we have multiple Component then we use children

@ViewChildren(ChildComponent) children:? QueryList< ChildComponent >
@ViewChildren(‘button’) buttonsRef?: QueryList< ElementRef<HTMLButtonElement>>

We can access these in lifecycle hook ngAfterView Init

ngAfterViewInit(){
this.children.forEach(child=>{
Console.log(child);
child.method();
child.property = 5;
})
}

--

--

Anil Kumar
Anil Kumar

Written by Anil Kumar

Software Engineer| Angular Advocate | Cyclist

No responses yet