0
0
Angularframework~30 mins

Effect for side effects in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Effect for Side Effects in Angular Signals
📖 Scenario: You are building a simple Angular standalone component that tracks a user's name and shows a greeting message. You want to log a message to the console every time the user's name changes, using Angular's effect function for side effects.
🎯 Goal: Create an Angular standalone component that uses a signal to store the user's name and an effect to log a message to the console whenever the name changes.
📋 What You'll Learn
Create a signal called userName with the initial value '' (empty string).
Create a signal called greeting that returns `Hello, ${userName()}`.
Use Angular's effect function to log `User name changed to: ${userName()}` whenever userName changes.
Create a standalone Angular component named UserGreetingComponent with a template that includes an input bound to userName and displays the greeting.
💡 Why This Matters
🌍 Real World
Using Angular signals and effects helps build reactive user interfaces that respond to user input and other changes efficiently.
💼 Career
Understanding Angular signals and effects is important for modern Angular development, especially for building clean, reactive components with side effects like logging or API calls.
Progress0 / 4 steps
1
Create the userName signal
Create a signal called userName with the initial value '' (empty string) inside the UserGreetingComponent.
Angular
Need a hint?

Use signal('') to create a signal with an empty string.

2
Create the greeting signal
Inside UserGreetingComponent, create a signal called greeting that returns the string `Hello, ${userName()}` using an arrow function.
Angular
Need a hint?

Use computed(() => `Hello, ${this.userName()}`) to create a computed signal.

3
Add an effect to log changes
Import effect from @angular/core and inside UserGreetingComponent create an effect that logs `User name changed to: ${userName()}` whenever userName changes.
Angular
Need a hint?

Use effect(() => { ... }) inside the constructor to watch userName.

4
Add template with input and greeting display
Add a template to UserGreetingComponent with an <input> element bound to userName using [ngModel] and (ngModelChange), and a <p> element that displays the greeting() signal.
Angular
Need a hint?

Use [ngModel]="userName()" and (ngModelChange)="userName.set($event)" on the input, and display {{ greeting() }} in a paragraph.