Bird
0
0

You want to create a component that projects a list of items and highlights the first projected item after content initialization. Which approach correctly uses ngAfterContentInit to achieve this?

hard📝 lifecycle Q15 of 15
Angular - Lifecycle Hooks
You want to create a component that projects a list of items and highlights the first projected item after content initialization. Which approach correctly uses ngAfterContentInit to achieve this?
import { Component, AfterContentInit, ContentChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'highlight-list',
  template: ``
})
export class HighlightList implements AfterContentInit {
  @ContentChildren('item') items!: QueryList;

  ngAfterContentInit() {
    // What should go here?
  }
}

Options for ngAfterContentInit implementation:
Adocument.querySelector('item').style.backgroundColor = 'yellow';
Bthis.items.nativeElement.style.backgroundColor = 'yellow';
Cthis.items[0].nativeElement.style.backgroundColor = 'yellow';
Dthis.items.first.nativeElement.style.backgroundColor = 'yellow';
Step-by-Step Solution
Solution:
  1. Step 1: Understand ContentChildren and QueryList

    @ContentChildren('item') collects all projected elements with template ref #item into a QueryList. Access the first element with items.first.
  2. Step 2: Apply style to first projected item

    Use items.first.nativeElement.style.backgroundColor to highlight the first item safely after content is initialized.
  3. Step 3: Evaluate other options

    this.items.nativeElement.style.backgroundColor = 'yellow'; is invalid because QueryList has no nativeElement property. this.items[0].nativeElement.style.backgroundColor = 'yellow'; is invalid because QueryList is not an array. document.querySelector('item').style.backgroundColor = 'yellow'; uses direct DOM query which breaks Angular encapsulation.
  4. Final Answer:

    this.items.first.nativeElement.style.backgroundColor = 'yellow'; -> Option D
  5. Quick Check:

    Use QueryList.first to access first projected element [OK]
Quick Trick: Use QueryList.first, not array or direct DOM, to access projected items [OK]
Common Mistakes:
  • Treating QueryList as an array
  • Using direct DOM queries instead of Angular references
  • Accessing nativeElement on QueryList itself

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes