@ViewChild is used in a parent component to access a child component or a DOM element directly.
typescript
// child.component.ts
export class ChildComponent {
message = 'Hello from Child!';
showAlert() {
alert('Child method called!');
}
}
// parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
<button (click)="callChildMethod()">Call Child</button>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child.message);
}
callChildMethod() {
this.child.showAlert();
}
}You should see
(The parent can directly access the child component's properties and methods)