How to use @ViewChild in Angular
Using @ViewChild decorator enables direct access to child components and DOM elements from parent components for programmatic control and method invocation. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented @ViewChild in countless Angular components for modal controls, form validation, and dynamic content management. From my expertise, the most effective approach is using @ViewChild with template reference variables for clean component interaction. This method provides direct access to child component properties and methods without complex event handling.
Use @ViewChild
decorator with template reference variables to access child components and DOM elements.
// parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core'
import { ChildComponent } from './child.component'
@Component({
selector: 'app-parent',
template: `
<child-component #childRef></child-component>
<input #inputRef type="text" placeholder="Enter text">
<button (click)="callChildMethod()">Call Child Method</button>
<button (click)="focusInput()">Focus Input</button>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild('childRef') childComponent!: ChildComponent
@ViewChild('inputRef') inputElement!: ElementRef<HTMLInputElement>
ngAfterViewInit() {
// Access child component after view initialization
console.log('Child component:', this.childComponent)
}
callChildMethod() {
this.childComponent.performAction()
}
focusInput() {
this.inputElement.nativeElement.focus()
}
}
// child.component.ts
@Component({
selector: 'child-component',
template: '<p>Child Component</p>'
})
export class ChildComponent {
performAction() {
console.log('Action performed in child!')
}
}
The @ViewChild decorator queries the component template for elements matching the specified selector. Use template reference variables with # syntax to mark elements for access. Access ViewChild references in ngAfterViewInit lifecycle hook when the view is fully initialized.
Best Practice Note:
This is the same @ViewChild approach we use in CoreUI Angular components for modal and dropdown controls. Always implement AfterViewInit interface and access ViewChild references only after view initialization to avoid undefined errors.