In Angular ViewChild Documentation , it is mentioned that:
The following selectors are supported:
Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
In which use-case, child component provider need to be selector in ViewChild in parent component? I am not able to think of use-case of this functionality provided. I am not able search it over internet as well.
Angular University Blog about ViewChild Decorator also has no mention of this.
ViewChild makes it possible to access a child component and call methods or access instance variables that are available to the child.
Let’s say we have a ChildComponent. Ideally, you will use @angular/cli to generate your component:
Otherwise, you may need to create child.component.css and child.component.html files and manually add it to app.module.ts:
We will add a whoAmI method to ChildComponent which returns a message:
child.component.ts
Next, we will reference the component in our app template:
app.component.html
<app-child>child works!</app-child>
Now, we can call the whoAmI method from within our parent component class with ViewChild like this:
When viewing the application in a browser, the console log will display:
Output
The parent component was able to call the child component’s whoAmI method.