Search code examples
angularngrx

How do I transfer values from the store to the form?


I get data from store in this way:

  ngOnInit(): void {
    this.store.pipe(select(getPerson))
    this.store.dispatch(loadPerson());
  }

But I need to be able to transfer data from the store to the form.

Here is an example of how a request is executed without ngrx:

formPerson: FormGroup = this.fb.group({});

this.personService.fetch()
.pipe(
  tap((user) => {
    this.formPerson.get('username')?.setValue(user['username']);
    this.formPerson.get('full_name')?.setValue(user['full_name']);
    this.formPerson.get('email')?.setValue(user['email']);
    this.formPerson.get('phone')?.setValue(user['phone']);
  })
)

Solution

  • I usually just add a subscription

    person$: Observable<Person>;
    personSubscription: Subscription;
    formPerson: FormGroup = this.fb.group({});
    
    ngOnInit(): void {
     person$ = this.store.pipe(select(getPerson));
     
     //Subscribe
     personSubscription = this.person$.subscribe(person => {
         if (person) {
           this.formPerson.get('username')?.setValue(user['username']);
           this.formPerson.get('full_name')?.setValue(user['full_name']);
           this.formPerson.get('email')?.setValue(user['email']);
           this.formPerson.get('phone')?.setValue(user['phone']);
         }
     });
    
     this.store.dispatch(loadPerson());
    }
    

    Dont forget to unsubcribe on the destroy

    ngOnDestroy(): void {
      this.personSubscription.unsubscribe();
    }
    

    }