Bird
0
0

You want to change the background color of a child component's element after it is fully rendered. Which approach correctly uses ngAfterViewInit to do this in the parent component?

hard📝 lifecycle Q15 of 15
Angular - Lifecycle Hooks
You want to change the background color of a child component's element after it is fully rendered. Which approach correctly uses ngAfterViewInit to do this in the parent component?
Child component template:
<div #childBox>Child Content</div>

Parent component code options:
AUse @ViewChild('childBox') in parent and change style in ngAfterViewInit
BChange child element style directly in parent's ngOnInit
CUse @ViewChild in parent and change style in constructor
DModify child element style in parent's ngAfterContentInit without @ViewChild
Step-by-Step Solution
Solution:
  1. Step 1: Understand when child view elements are ready

    Child component's view elements are accessible in the parent during ngAfterViewInit, after the parent's view and child views are fully initialized.
  2. Step 2: Identify correct lifecycle hook and access method

    Using @ViewChild in the parent to get the child's element reference and modifying it in ngAfterViewInit ensures the element is ready and safe to modify.
  3. Final Answer:

    Use @ViewChild('childBox') in parent and change style in ngAfterViewInit -> Option A
  4. Quick Check:

    Modify child view in parent's ngAfterViewInit with @ViewChild [OK]
Quick Trick: Use @ViewChild and ngAfterViewInit to access child elements [OK]
Common Mistakes:
  • Trying to access child elements in ngOnInit or constructor
  • Modifying child elements without @ViewChild reference
  • Using ngAfterContentInit which is for projected content, not view

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes