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:
ng generate component child --flat
Otherwise, you may need to create child.component.css and child.component.html files and manually add it to app.module.ts:
app.module.ts
import { ChildComponent } from './child.component';
...
@NgModule({
declarations: [
AppComponent,
ChildComponent
],
...
})
We will add a whoAmI method to ChildComponent which returns a message:
child.component.ts
whoAmI() {
return 'I am a child component!';
}
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:
app.component.ts
import {
Component,
ViewChild,
AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child.whoAmI()); // I am a child component!
}
}
When viewing the application in a browser, the console log will display:
Output
I am a child component!
The parent component was able to call the child component’s whoAmI method.
ViewChild
to think of them all. Some angular features stay untouched in projects forever, but that doesn't mean that only because you never have to use them, that they are entirely useless. – Mike S.