📖 Scenario: You are building a simple Angular component that receives a user's name as input. You want to detect when the input changes and update a message accordingly.
🎯 Goal: Create an Angular component that uses ngOnChanges to detect changes to an input property called userName and updates a message displayed in the template.
📋 What You'll Learn
Create a standalone Angular component named UserGreetingComponent
Add an input property called userName of type string
Implement the ngOnChanges lifecycle hook to detect changes to userName
Update a component property greetingMessage inside ngOnChanges to say Hello, {userName}!
Display the greetingMessage in the component template
💡 Why This Matters
🌍 Real World
Detecting input changes is common in Angular apps to react when parent components send new data to child components, such as updating user info or settings.
💼 Career
Understanding ngOnChanges is essential for Angular developers to manage component communication and lifecycle effectively.
Progress0 / 4 steps
1
Create the Angular component with input property
Create a standalone Angular component named UserGreetingComponent with an input property called userName of type string. Import Component and Input from @angular/core. The component should have a template that displays greetingMessage inside a <p> tag.
Angular
Hint
Remember to import Input and decorate userName with @Input(). Initialize greetingMessage as an empty string.
2
Add ngOnChanges lifecycle hook
Import OnChanges and SimpleChanges from @angular/core. Make UserGreetingComponent implement OnChanges. Add the ngOnChanges method with a parameter changes of type SimpleChanges.
Angular
Hint
Import OnChanges and SimpleChanges and add implements OnChanges after the class name.
3
Update greetingMessage inside ngOnChanges
Inside the ngOnChanges method, check if userName has changed using changes['userName']. If it has, update greetingMessage to the string Hello, {userName}! using a template literal.
Angular
Hint
Use if (changes['userName']) to detect changes and update greetingMessage with a template literal.
4
Complete the component with accessibility and styling
Add an aria-live="polite" attribute to the <p> tag in the template to announce changes to screen readers. Also, add a CSS class greeting to the <p> tag for styling.
Angular
Hint
Add aria-live="polite" and a CSS class greeting to the <p> tag in the template.
Practice
(1/5)
1. What is the primary purpose of the ngOnChanges lifecycle hook in Angular?
easy
A. To handle user events like clicks
B. To initialize component variables after creation
C. To respond whenever an input property changes value
D. To destroy the component before removal
Solution
Step 1: Understand the role of ngOnChanges
The ngOnChanges hook is called when Angular detects changes to input properties of a component.
Step 2: Compare with other lifecycle hooks
Other hooks like ngOnInit initialize data, but ngOnChanges specifically reacts to input changes.
Final Answer:
To respond whenever an input property changes value -> Option C
Quick Check:
ngOnChanges = input change response [OK]
Hint: ngOnChanges runs when inputs change, not on init [OK]
Common Mistakes:
Confusing ngOnChanges with ngOnInit
Thinking it handles user events
Assuming it runs on component destruction
2. Which of the following is the correct method signature for ngOnChanges in an Angular component?
easy
A. ngOnChanges(changes: SimpleChanges): void
B. ngOnChanges(): void
C. ngOnChanges(changes: ChangeDetectorRef): void
D. ngOnChanges(event: Event): void
Solution
Step 1: Recall the ngOnChanges signature
The ngOnChanges method receives a parameter of type SimpleChanges which holds the changes.
Step 2: Verify parameter type and return
The method returns void and the parameter must be SimpleChanges, not other types.
Final Answer:
ngOnChanges(changes: SimpleChanges): void -> Option A
A. ngOnChanges must have a parameter of type SimpleChanges
B. The @Input decorator is missing parentheses
C. ngOnChanges should return a value
D. data property must be initialized
Solution
Step 1: Check ngOnChanges method signature
The ngOnChanges method must accept a parameter of type SimpleChanges to receive input changes.
Step 2: Verify other parts
The @Input decorator syntax is correct, no return value is needed, and data can be uninitialized initially.
Final Answer:
ngOnChanges must have a parameter of type SimpleChanges -> Option A
Quick Check:
ngOnChanges(SimpleChanges) required [OK]
Hint: Always include SimpleChanges parameter in ngOnChanges [OK]
Common Mistakes:
Omitting the SimpleChanges parameter
Expecting ngOnChanges to return a value
Misusing @Input decorator syntax
5. You want to reset a component's internal counter to zero whenever the input resetFlag changes from false to true. Which ngOnChanges implementation correctly achieves this?
export class CounterComponent implements OnChanges {
@Input() resetFlag = false;
@Input() otherValue: number = 0;
counter = 10;
ngOnChanges(changes: SimpleChanges) {
// Which option resets counter correctly?
}
}
hard
A. if (this.resetFlag) { this.counter = 0; }
B. if (changes['resetFlag'] && changes['resetFlag'].previousValue === true) { this.counter = 0; }
C. if (changes['resetFlag'].previousValue === false) { this.counter = 0; }
D. if (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; }
Solution
Step 1: Detect resetFlag input change to true
We must check if resetFlag changed and its new value is true.
Step 2: Verify condition logic
if (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; } checks both existence of change and currentValue === true, correctly resetting counter.
Step 3: Analyze other options
if (this.resetFlag) { this.counter = 0; } checks current value but runs on any input change, incorrectly resetting if resetFlag is true when other inputs change. if (changes['resetFlag'].previousValue === false) { this.counter = 0; } accesses changes['resetFlag'] without checking existence, causing runtime error when other inputs change. if (changes['resetFlag'] && changes['resetFlag'].previousValue === true) { this.counter = 0; } checks previous true, wrong condition.
Final Answer:
if (changes['resetFlag'] && changes['resetFlag'].currentValue === true) { this.counter = 0; } -> Option D
Quick Check:
Check currentValue true on input change [OK]
Hint: Check currentValue === true in changes to reset [OK]
Common Mistakes:
Ignoring previousValue and currentValue difference
Resetting counter on wrong condition
Not checking if changes object has resetFlag
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.