import { Component, signal, effect } from '@angular/core'; @Component({ selector: 'app-sample', standalone: true, template: `<p>{{ count() }}</p>` }) export class SampleComponent { count = signal(0); constructor() { console.log('constructor'); } ngOnInit() { console.log('ngOnInit'); } ngAfterViewInit() { console.log('ngAfterViewInit'); } }
The constructor runs first when Angular creates the component instance. Lifecycle hooks like ngOnInit run after the constructor during initialization.
import { Component, signal, effect } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, template: `<button (click)="increment()">Increment</button>` }) export class CounterComponent { count = signal(0); constructor() { effect(() => { console.log('Effect:', this.count()); }); } increment() { this.count.update(c => c + 1); } }
The effect runs once immediately logging the initial value 0. After clicking the button, the signal updates to 1, triggering the effect again.
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-toggle', standalone: true, template: ` <button (click)="toggle()">Toggle</button> @if (visible()) { <section>Visible Content</section> } ` }) export class ToggleComponent { visible = signal(false); constructor() { console.log('constructor'); } ngOnInit() { console.log('ngOnInit'); } ngAfterViewInit() { console.log('ngAfterViewInit'); } toggle() { this.visible.update(v => !v); } }
The constructor runs first to create the component instance. Then ngOnInit runs after inputs are set. Finally, ngAfterViewInit runs after the view is fully initialized, including the @if block.
Option D tries to use count.set(count + 1), but count is a signal function, not a number. You must use count.update(c => c + 1) or count.set(newValue) with a number.
ngAfterViewInit hook never logs. Why?import { Component, signal, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-hidden', standalone: true, template: ` @if (visible()) { <section>Content</section> } ` }) export class HiddenComponent implements AfterViewInit { visible = signal(false); constructor() { console.log('constructor'); } ngAfterViewInit() { console.log('ngAfterViewInit'); } }
Angular only calls lifecycle hooks if the component class implements the corresponding interface. Without implements AfterViewInit, ngAfterViewInit is not called.