Lifecycle & Projection — Series 3

Preview — 3 of 10 questions

userId goes from 1 to 2. What does this log?

javascript
ngOnChanges(changes: SimpleChanges) {
  if (changes['userId']) {
    console.log(changes['userId'].previousValue, '->', changes['userId'].currentValue);
  }
}
A1 -> 2 — SimpleChange carries both the value the input had before this change and the value it has now, keyed by the input's name in the SimpleChanges map
B2 -> 2 — both fields always reflect the latest value
Cundefined -> 2, because previousValue is only populated on the very first change
DThis throws, because changes['userId'] is only defined when the value actually changes structurally, not for primitives

Does *ngIf still work correctly on content that gets projected this way?

javascript
// card.component.html
<div class="card"><ng-content></ng-content></div>
ANo — <ng-content> freezes projected content as static markup; *ngIf is ignored once it crosses into a slot
BYes, but only if CardComponent explicitly re-evaluates it
CYes — projected content is compiled in the parent's context and remains a live, fully functional part of the parent's view; *ngIf, event bindings, and interpolation inside it all keep working exactly as if it weren't projected at all. <ng-content> only changes where that already-live content is rendered, not how it behaves
DNo — structural directives require the content to be a direct child of the component that renders them, not passed through projection

Both querying decorators are used, but they're read in two different lifecycle hooks. Why?

javascript
@ContentChild(TabComponent) tab!: TabComponent;
@ViewChild(HeaderComponent) header!: HeaderComponent;
A@ContentChild targets content projected in from the parent, which finishes being composed before the component's own view does; Angular fires ngAfterContentInit once projected content is resolved, and ngAfterViewInit later, once the component's own template (including @ViewChild targets) has finished initializing — reflecting the actual order those two things become available
BIt's arbitrary — either query could be read in either hook
C@ViewChild always resolves first because view children are declared inside the component's own file
D@ContentChild is deprecated in favor of @ViewChild and this code shouldn't use both

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.