1

In Angular 11, What is the best approach to getting updates from properties in a shared service when using Reactive Forms?

If one component updates values in the service, how is the other component supposed to get the change without changing everything to Subjects and then patching the existing form?

I define the form:

<form [formGroup]="form" class="form-horizontal" role="form">
<div formGroupName="user">
    <mat-form-field>
        <input matInput formControlName="name" placeholder="Username">
    </mat-form-field>
    <mat-form-field>
        <input matInput formControlName="fullName" placeholder="Full Name">
    </mat-form-field>
</div>
createForm() {
this.form = this.fb.group({
  user: this.fb.group({
    name: [this.userService.currentUser.name],
    fullName: [this.userService.currentUser.fullName]
  }),
});

}

This is just an example, but how would I update this component's form if the value in userService.fullName changed? I could use Subject, but then I have to always set the currentUser and cannot just update sub properties and in more complex objects, things seem to get messier.

I could just use Template driven forms for this, but then the validation is more complex. Is there a better way to do this?

Similar to this question, but I have not really seen a good answer.

Gabe
  • 122
  • 5

1 Answers1

1

Service to FormGroup (or any Form element) : patchValue or setValue (partial or full update)

FormGroup (or any Form element) to Service : valueChanges

// FormGroup to service (don't forget to unsubscribe)
this.myFormGroup.valueChanges.subscribe(data => this.service.updateData(data));

// Service to FormGroup (don't forget to unsubscribe)
this.service.data$.subscribe(data => this.myFormGroup.patchValue(data));
Chaniro
  • 399
  • 1
  • 8
  • It is not about getting the data from the current component and saving it specifically. If two components are both using data from the same service. What do I do when I save it from component 1 and then component 2's form has already been initialized so it does not update when component 1 saves its data. Am I supposed to go trigger form updates to all components using the service data? – Gabe Aug 02 '21 at 20:58
  • As I understand : you have 2 components (forms) which use the same data in their FormGroup. When one of them is saving data, you want to update all components (override), right ? You should use an Observable to store your data in your service and update your FormGroups when you receive new data from this Observable. – Chaniro Aug 03 '21 at 09:49