Search code examples
angularrxjsangular8angular-reactive-forms

get first values of an dynamically built reactive form


I have an form component where I build a dynamic form with values of a service call. That works correctly.

Now I want to display these values in a different component.

I tried to solve this problem with an Event Emitter and form.valueChanges.

ngOnInit():void {
 this.myForm.valueChanges.pipe(
  takeUntil(this.destroyed$)
 ).subscribe(_ => {

 // calls the eventemitter
 this.emit();
 });
}

This works quite well but not exactly what I want, because the problem is the values only get emitted when the form changed. Meaning my form is built and renderd, but in the other component no values are displayed. Then I change one value in the form the other component displays the values of the form. (Naturally because of the valueChanges)

How do I also get the "patched" values from the form which came from the service call? And no I can't use the observable of the service call in the displaying component.


Solution

  • Use rxjs startsWith operator like this to emit value when form created with value

    Try this:

    ngOnInit():void {
     this.myForm.valueChanges.pipe(
      startsWith(this.myForm.value),
      takeUntil(this.destroyed$)
     ).subscribe(_ => {
    
     // calls the eventemitter
     this.emit();
     });
    }