What is the process for moving data from the store to the form?

When retrieving data from the store, I typically use the following method:

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

However, I am now faced with the challenge of transferring this data from the store to a form.

Here is an alternative approach using a service 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']);
  })
)

Answer №1

In case the service is returning property names that match those in an angular reactive form, you can utilize this approach:

<pre>this.store.pipe(select(getUser),filter(data=>data!=null))
      .subscribe((user) => {
        this.userForm.patchValue(user);
      })
</pre>

Answer №2

My usual method is to include 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());
}

Remember to unsubscribe during destruction

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

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between Angular services and exportsIn Angular,

I have a collection of straightforward tool functions that do not require sharing state across the application, do not need to be singleton instances, and do not rely on injected services. Is there any benefit to using an injectable service like: @Inject ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

How to access objects in Angular2 without using pipe or ngFor

Suppose I have the following data in an asymmetric array: [{'name':'user','password':'123'},{'title':'officer','grade':'5','age':'5'}] which is obtained f ...

Angular CRUD Form Data Conversion Update

After selecting the date 3/2/2021 in my Angular create CRUD form, it gets passed to MongoDB as 2021-03-02T00:00:00.000+00:00 and then displayed on the update CRUD form as 2021-03-02T00:00:00.000Z. How can I convert this to 'M/d/yyyy' format? (I ...

Adjusting a variable's value based on the changes of another variable

In the process of developing an application feature for managing favorites, I am integrating data from two different sources. One source is a const file that I am exporting as an observer (observerA$), while the other source is a database containing only t ...

Exploring the capabilities of Angular and Django Rest Framework applications

Imagine having a front-end application built in React and a back-end application developed using Node.js with Express. The back end has been thoroughly tested with Mocha, and now it's time to create functional tests for the front end. However, since t ...

Impact of using ngIf in ngAfterViewInit

During the ngAfterViewInit lifecycle hook, I am triggering an event and capturing it in another component using ComponentRef. Everything functions smoothly until I incorporate ngIf in the parent component. What impact does ngIf have on Angular's life ...

Using a static value in the comparator is necessary for Array.find to function properly in Typescript

Looking to retrieve an item from an array: const device = this.selectedDevtype.devices.find(item => console.log(this.deviceID); return item.device_id === this.deviceID; }); console.log(device); When this.deviceID is logged, it shows "4", but t ...

When using Angular 2's HTTP POST method, it initiates an OPTIONS request

I've come across a peculiar issue with my Angular 2 application. I'm trying to send a JSON via a POST call to my Play Scala API, but it keeps attempting to make an OPTIONS request. Below is the code snippet : LoginService constructor (private ...

How can I retrieve query parameters passed from an Angular application in PHP?

I'm trying to figure out how to retrieve data from query parameters sent by an Angular application in PHP. Unfortunately, I don't have much experience with PHP. Is there anyone willing to lend a hand? ...

Sending an Angular signal value from a component input to a service

During some experimentation with Angular 17 and signals, I encountered a scenario that I'm unsure how to tackle without resorting to ngOnChanges and @Input handling. Imagine you have a component with input signals, and you want to replicate or set th ...

Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search produ ...

Angular error validation for enforcing minimum and maximum lengths

this.employeeForm = this.fb.group({ fullName: [ '', [ Validators.required, Validators.minLength(2), Validators.maxLength(10), ], ], email: [''], skills: this. ...

Merging Two Individual Applications into a Single Application Using Angular 8

Recently started learning Angular as a beginner. I am currently working on developing an application and opted to utilize the Angular Multikart ecommerce template. This template comes with separate front-end and admin-end sections, which I can currently ...

Error: Can't access the 'http' property because it's undefined in Angular 2

Recently, I successfully integrated the gapi client into my Angular 2 application. However, I am now facing an issue where my http object is showing as undefined and I can't seem to figure out why. Here's the snippet of code that's causing ...

Generate an event specifically for weekdays using the angular-calendar tool available at https://mattlewis92.github.io/angular-calendar/#/kitchen-sink

I'm currently setting up events for the calendar using . According to the guidelines, events are structured like this : events: CalendarEvent[] = [ { start: subDays(startOfDay(new Date()), 1), end: addDays(new Date(), 1), title ...

Having trouble correctly initializing RequestOptionsArgs for a POST request in the service function

Recently, I have been working with Angular 6 and decided to follow a helpful video tutorial on image submissions (link to the video). My goal is to track the progress of the form submission in order to display the percentage of the uploaded file. In my c ...

Leveraging the angular-in-memory-web-api in conjunction with Angular CLI

Encountering some frustrating issues while trying to integrate angular-in-memory-web-api into my Angular 2 project that was built using Angular CLI. Here's the current structure of dependencies inside my package.json: "dependencies": { "@angular/co ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...