Recall & Review
beginner
What is the purpose of the
ngAfterViewInit lifecycle hook in Angular?It runs after Angular has fully initialized a component's view and its child views. It's used to perform actions that require the view to be ready, like accessing DOM elements or child components.
Click to reveal answer
beginner
When exactly does
ngAfterViewInit get called in the component lifecycle?It is called once after Angular initializes the component's views and child views, right after
ngAfterContentInit and before the view is displayed to the user.Click to reveal answer
intermediate
Why should you avoid manipulating the DOM directly in the constructor or
ngOnInit?Because the component's view and child views are not fully initialized yet, so DOM elements might not exist or be ready.
ngAfterViewInit is the safe place for DOM access.Click to reveal answer
intermediate
How can you use
ngAfterViewInit to access a child component or DOM element?You can use Angular's
@ViewChild decorator to get a reference to the child component or element, then safely interact with it inside ngAfterViewInit.Click to reveal answer
advanced
What happens if you try to update a component's data-bound property inside
ngAfterViewInit without triggering change detection?Angular may throw an error because the view has already been checked. To fix this, you can use
ChangeDetectorRef.detectChanges() to update the view safely.Click to reveal answer
When is
ngAfterViewInit called in Angular?✗ Incorrect
ngAfterViewInit runs after Angular initializes the component's view and child views, making it the right place to access the DOM or child components.
Which decorator is commonly used with
ngAfterViewInit to access child components or elements?✗ Incorrect
@ViewChild lets you get a reference to a child component or DOM element, which you can safely use inside ngAfterViewInit.
Why should DOM manipulation be done in
ngAfterViewInit instead of ngOnInit?✗ Incorrect
The component's view and child views are not ready in ngOnInit, so DOM elements might not exist yet. ngAfterViewInit ensures the view is ready.
What might happen if you update a data-bound property inside
ngAfterViewInit without triggering change detection?✗ Incorrect
Angular may throw an error because the view was already checked. You can fix this by calling ChangeDetectorRef.detectChanges() after the update.
Which lifecycle hook runs immediately before
ngAfterViewInit?✗ Incorrect
ngAfterContentInit runs after content projection but before the view initialization, so it runs just before ngAfterViewInit.
Explain in your own words why
ngAfterViewInit is the right place to access DOM elements or child components in Angular.Think about when the view is ready to be used.
You got /4 concepts.
Describe a scenario where updating a property inside
ngAfterViewInit causes an error and how to fix it.Angular checks the view before and after lifecycle hooks.
You got /3 concepts.