Consider this Angular component code snippet. What will be the value of message after ngOnInit runs?
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-welcome', template: `<p>{{ message }}</p>`, standalone: true }) export class WelcomeComponent implements OnInit { message = ''; ngOnInit() { this.message = 'Hello from ngOnInit!'; } }
ngOnInit runs after the component is created but before it is displayed.
The ngOnInit method sets the message property to "Hello from ngOnInit!" before the template renders. So the displayed message will be this string.
Choose the correct timing for when ngOnInit is called in an Angular component's lifecycle.
Think about when initialization logic should run relative to component creation.
ngOnInit runs once after the constructor and before the component is displayed. It is the right place for initialization logic.
Which option correctly implements ngOnInit in this Angular component?
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-counter', template: `<p>{{ count }}</p>`, standalone: true }) export class CounterComponent implements OnInit { count = 0; // ngOnInit implementation goes here }
Remember the correct method syntax inside a class in TypeScript.
Option B uses the correct method syntax for ngOnInit. Options A, B, and D have syntax errors or invalid method declarations.
Given this Angular component, why does the template not show the updated title after ngOnInit?
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-title', template: `<h1>{{ title }}</h1>`, standalone: true }) export class TitleComponent implements OnInit { title = 'Initial'; ngOnInit() { let title = 'Updated in ngOnInit'; } }
Check variable scope inside ngOnInit.
The let title inside ngOnInit creates a new local variable that hides the class property. The class property title remains unchanged, so the template shows the initial value.
Why should you put initialization code in ngOnInit rather than the constructor in Angular components?
Think about when Angular sets input properties relative to constructor and ngOnInit.
The constructor runs before Angular sets input properties, so they may be undefined there. ngOnInit runs after inputs are set, so it is safe to use them for initialization.