0
0
Angularframework~30 mins

ngOnChanges for input changes in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Detect Input Changes with ngOnChanges in Angular
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Add aria-live="polite" and a CSS class greeting to the <p> tag in the template.