angularangular-reactive-forms

Set default value of reactive form once observable returns


I have some code ngOnInit that uses a routing variable to filter an observable array for a specific object:

this.route.paramMap.subscribe(params => { // Wrapper to get route param (ID)

  this.store.dispatch(new fromStore.LoadObjects());
  this.object$ = this.store.select(fromStore.getAllObjects).pipe(
    map(
      objects => objects.filter(o => o.id === params.get('id'))[0]
    )
  );

})

Then I have the following to initialize a form:

this.objectDataForm = this.formBuilder.group({
  'name':     ['', Validators.required ],
  'location': ['', Validators.required ]
});

I want to somehow connect my observable object to the form data to bring in as a default value. I think I need patchValue:

this.objectDataForm.patchValue({
  name: myValue1, 
  location: myValue2
});

But I cannot figure out how to put this patch value in a place where it gets the value at the right time and delivers it to the form. I could easily be nuking this...


Solution

  • You can make use of take(1) operator. See here.

    The flow would be: