Two-way bind a Signal Input object value with [(ngModel)]
Recently, I encountered this challenge... Refactor a form component to Angular Signals. The old form component works like this: The form data comes from a reactive state service The form data is an object The form data is cloned before it is passed to the form component The form component receives the form data via one classic decorator-based Angular @Input @Input({required: true}) user!: User; The form uses [(ngModel)] to mutate the form data object First Name Clicking the save button would send the mutated object to the parent component via an Angular @Output The parent component updates the reactive state service This setup works great in many of our applications. You can review this setup in this StackBlitz which showcases the basic principle: Form with classic Angular @Input Refactor to Signal Input With Angular Signal Input we can make our component inputs reactive. This sounds great! FYI Signal Inputs are the recommended way for new projects. From the Angular docs: Let's refactor our classic Angular @Input to a Signal Input: user = input.required(); Signal Input object value and [(ngModel)] The Signal Input receives an object of type User. We try to bind to the object properties with [(ngModel)]. This code looks so nice
![Two-way bind a Signal Input object value with [(ngModel)]](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy8uorrbgpt7rqo9k76uf.png)
Recently, I encountered this challenge... Refactor a form component to Angular Signals.
The old form component works like this:
- The form data comes from a reactive state service
- The form data is an object
- The form data is cloned before it is passed to the form component
- The form component receives the form data via one classic decorator-based Angular @Input
@Input({required: true})
user!: User;
- The form uses [(ngModel)] to mutate the form data object
id="firstName" name="firstName" [(ngModel)]="user.firstName" />
- Clicking the save button would send the mutated object to the parent component via an Angular @Output
- The parent component updates the reactive state service
This setup works great in many of our applications.
You can review this setup in this StackBlitz which showcases the basic principle: Form with classic Angular @Input
Refactor to Signal Input
With Angular Signal Input we can make our component inputs reactive. This sounds great!
FYI Signal Inputs are the recommended way for new projects. From the Angular docs:
Let's refactor our classic Angular @Input to a Signal Input:
user = input.required<User>();
Signal Input object value and [(ngModel)]
The Signal Input receives an object of type User. We try to bind to the object properties with [(ngModel)]
.
This code looks so nice