How does the newer signal based viewChild function differ from the traditional ViewChild decorator?
Short answer
The viewChild function returns a signal instead of a plain property, letting you read the referenced element or component reactively, and it can be marked as required, causing a clear error if the referenced element is unexpectedly missing, rather than silently being undefined.
Advertisement
AModel answer
The viewChild function returns a signal instead of a plain property, letting you read the referenced element or component reactively, and it can be marked as required, causing a clear error if the referenced element is unexpectedly missing, rather than silently being undefined.
import { viewChild } from '@angular/core';
export class ParentComponent {
child = viewChild.required(ChildComponent);
ngAfterViewInit() {
console.log(this.child()); // called as a function, since it is a signal
}
}Real-world example
A parent component uses the newer signal based viewChild function to access a required child component, getting a clear, immediate error during development if that child component is ever accidentally removed from the template.
Likely follow-ups
- What specific benefit does marking a viewChild as required actually provide over the traditional decorator?
- Can viewChild signals be combined with computed signals for derived values?
Related topics