What is Angular content projection with ng-content?
Why Interviewers Ask This
This tests whether you can apply Angular knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Content projection allows a component to receive and render HTML content from its parent, making components more flexible and reusable. The component defines slot(s) where the projected content appears using <ng-content>. Basic projection: component template: <div class="card"> <div class="card-header">{{ title }}</div> <div class="card-body"> <ng-content></ng-content> </div> </div>. Usage: <app-card [title]="heading"> <p>This content is projected into the card body.</p> </app-card>. Multi-slot projection: use the select attribute to project content into named slots: <ng-content select="[card-header]"></ng-content> <ng-content select=".card-body-content"></ng-content> <ng-content></ng-content> <!-- fallback -->. Usage: <app-card> <h2 card-header>Title</h2> <p class="card-body-content">Body</p> </app-card>. ng-content with component selector: <ng-content select="app-header"> — project only app-header components. ngProjectAs: makes an element appear as if it has a different selector for ng-content matching. Accessing projected content: use @ContentChild / @ContentChildren in the component class. ngTemplateOutlet: project template references: <ng-container *ngTemplateOutlet="headerTemplate"> — more dynamic than ng-content.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Angular codebase.
More Angular Questions
View all →- Intermediate What is RxJS and how is it used in Angular?
- Intermediate What is the difference between switchMap, mergeMap, concatMap, and exhaustMap?
- Intermediate What is the difference between Subject, BehaviorSubject, ReplaySubject, and AsyncSubject?
- Intermediate What is the Angular NgRx state management library?
- Intermediate What is Angular lazy loading and preloading strategy?