Performance: @ViewChild decorator usage
This affects the DOM access timing and component rendering flow, impacting interaction responsiveness and layout stability.
export class MyComponent { @ViewChild('myElement', { static: true }) myElementRef!: ElementRef; ngOnInit() { console.log(this.myElementRef.nativeElement.textContent); } }
export class MyComponent { @ViewChild('myElement', { static: false }) myElementRef!: ElementRef; ngAfterViewInit() { setTimeout(() => { console.log(this.myElementRef.nativeElement.textContent); }, 0); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| @ViewChild with static: false and setTimeout | Delayed DOM query after view init | Multiple reflows due to delayed access | Higher paint cost from layout thrashing | [X] Bad |
| @ViewChild with static: true accessed in ngOnInit | Early DOM query before view init | Single reflow | Lower paint cost with stable layout | [OK] Good |
@ViewChild decorator in Angular?@ViewChild to get a reference to a template element with template variable #myInput? <input #myInput type="text" value="Hello">
export class MyComponent implements AfterViewInit {
@ViewChild('myInput') inputRef!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
console.log(this.inputRef.nativeElement.value);
}
}@ViewChild: export class MyComponent {
@ViewChild('myButton') buttonRef: ElementRef;
ngOnInit() {
this.buttonRef.nativeElement.click();
}
}focusInput() on a child component ChildComponent using @ViewChild. Which of the following is the correct way to do this safely after the view initializes?Pass the test and this pattern moves unknown