The best way to access the child component is @ViewChild .
Say you have an AppMainComponent with a nested ChildComponent from your example.
// app-main.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-main', template: ` <child-component /> ` }) export class AppMainComponent {}
You want to call a clear method from your ChildComponent.
// child.component.ts import { Component } from '@angular/core'; @Component({ selector: 'child-component', template: '{{ greeting }}' }) class ChildComponent { greeting: String = 'Hello World!'; clear() { this.greeting = null; } }
You can execute it by importing the ChildComponent class, the ViewChild decorator and the pass component class in it as a request. This way you will have access to the ChildComponent interface stored in the user variable. Here is an example:
// app-main.component.ts import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './components/child/child.component'; @Component({ selector: 'app-main', template: ` <child-component /> ` }) class ChildComponent { @ViewChild(ChildComponent) child: ChildComponent; clearChild() { this.child.clear(); } }
Note! The view of the child becomes available only after ngAfterViewInit .
The answer after Angular initializes component views and child views. Called once after the first ngAfterContentChecked (). Component hook.
If you want to automatically execute a method, you need to do this inside this life cycle.
You can also get QueryList child components through ViewChildren .
import { Component, ViewChildren, QueryList } from '@angular/core'; import { ChildComponent } from './components/child/child.component'; ... @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
QueryList can be very useful, for example. You can subscribe to changes for children.
It is also possible to create reference template variables and access them through the ViewChild decoder.