What does the ViewChild decorator do, and how would you use it to access a child component from a parent's TypeScript code?
Short answer
ViewChild lets a parent component get a direct reference to a child component or a DOM element within its own template, from inside the parent's TypeScript class, letting the parent call methods or read properties directly on that child.
Advertisement
AModel answer
ViewChild lets a parent component get a direct reference to a child component or a DOM element within its own template, from inside the parent's TypeScript class, letting the parent call methods or read properties directly on that child.
@Component({
selector: 'app-parent',
template: `<app-child #child></app-child><button (click)="child.doSomething()">Trigger</button>`
})
export class ParentComponent {
@ViewChild('child') child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}Real-world example
A parent component directly calls a reset method on a child form component using ViewChild, letting it clear the form's fields from a button located outside the child component itself.
Likely follow-ups
- Why is ViewChild data only reliably available starting in the ngAfterViewInit lifecycle hook?
- What is the difference between ViewChild and ViewChildren?
Related topics