In this blog post, we will learn about ViewChild and ContentChild in Angular.
Essentially ViewChild and ContentChild are used for component communication in Angular. Therefore, if a parent component wants access of child component then it uses ViewChild or ContentChild.
Any component, directive, or element which is part of a template is ViewChild and any component or element which is projected in the template is ContentChild.
ViewChild and ViewChildren
If you want to access following inside the Parent Component, use @ViewChild decorator of Angular.
- Child Component
- DOM Element
ViewChild returns the first element that matches the selector.
Let us assume that we have a component MessageComponent as shown in the below listing:
We are using MessageComponent inside AppComponent as shown in below listing:
In application, you will get the output as below:
Here, MessageComponent has become child of AppComponent. Therefore, we can access it as a ViewChild. Definition of ViewChild is:
“The Child Element which is located inside the component template”,
Here MessageComponent is located inside template of AppComponent, so it can be accessed as ViewChild.
We need to do following tasks:
- Import ViewChild and AfterViewInit from @angular/core
- Implement AfterViewInit life cycle hook to component class
- Create a variable with decorator @ViewChild
- Access that inside ngAfterViewInit life cycle hook
In the output console you will find reference of MessageComponent, also if you can notice that __proto__ of MessageComponnet is set to Object.