1

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...

Coltuxumab
  • 615
  • 5
  • 16

1 Answers1

1

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

The flow would be:

  • create a subscription from your object$.pipe(take(1)) stream
  • inside subscription, call patchValue
  • Note: you may want to call .patchValue({ ... }, { emitEvent: false }) if you wish to skip this initial setup when subscribing to form's valueChanges stream
Ngoc Nam Nguyen
  • 493
  • 6
  • 15