ngAfterViewInit lifecycle hook is triggered at what point during a component's lifecycle?The ngAfterViewInit hook runs once Angular has fully initialized the component's view and all child views. This means the template and child components are ready for DOM interaction.
ngOnInit. What is the likely outcome?During ngOnInit, child components and their views may not be fully initialized yet, so accessing their properties can lead to undefined or unexpected values.
ngAfterViewInit lifecycle hook?To use ngAfterViewInit, the component must implement the AfterViewInit interface and define the method with correct syntax including parentheses.
@ViewChild('myDiv') in ngOnInit cause an error?
@ViewChild('myDiv') myDivElement: ElementRef;
ngOnInit() {
console.log(this.myDivElement.nativeElement.textContent);
}@ViewChild references are set after the component's view is initialized, which happens after ngOnInit. Accessing them too early leads to undefined or errors.
export class DemoComponent implements OnInit, AfterViewInit {
ngOnInit() {
console.log('Init');
}
ngAfterViewInit() {
console.log('View Init');
}
}Angular calls ngOnInit first during component initialization, then ngAfterViewInit after the view is fully initialized.