Advanced Angular — Series 2

Preview — 3 of 10 questions

count is a signal read in the template of an OnPush component, and it is updated from a setTimeout. Does the view update?

javascript
@Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: `{{ count() }}` })
export class Counter {
  count = signal(0);
  ngOnInit() { setTimeout(() => this.count.set(1), 1000); }
}
AYes — reading a signal in a template registers that view as a consumer, so writing to it marks exactly those views dirty, independently of how the write was triggered
BNo — OnPush only re-renders on input changes or events, so a markForCheck() is required
COnly if the component also injects ChangeDetectorRef
DOnly outside the zone, via NgZone.runOutsideAngular

Why measure the DOM here rather than in ngAfterViewInit?

javascript
constructor() {
  afterNextRender(() => {
    this.width = this.el.nativeElement.getBoundingClientRect().width;
  });
}
AngAfterViewInit runs before the component's own template exists
BafterNextRender runs on every change detection cycle, which is what a measurement needs
CafterNextRender runs once, after the browser has rendered, and only in the browser — so it is skipped during server rendering, where layout measurement is meaningless and would crash
DThey are interchangeable; afterNextRender is the shorter spelling

What does this do, and what blocks on it?

javascript
bootstrapApplication(App, {
  providers: [
    provideAppInitializer(() => inject(ConfigService).load()),
  ],
});
AIt runs load() after the first route renders, in the background
BIt runs load() during bootstrap and, because the callback returns a promise, bootstrap waits for it — the app does not render until the config resolves
CIt registers a service worker that caches the config
DIt runs load() once per route navigation

Sign up free to play

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