Fill a dynamic form with a date sourced from the ngrx storage

How can I populate a form with data from the store if setValue and patchValue methods are not working?

export class MyComponent implements OnInit, OnDestroy {
 public newsletterToEdit$: Observable<NewNewsletter> =
    this.store.selectNewsletterToEdit();

 public form = this.fb.group({
    title: ['', Validators.required],
    subtitle: ['', Validators.required],
    message: ['', Validators.required],
    users: [''],
    groups: [''],
    searchedUsers: [''],
    searchedGroups: [''],
    allowReplies: [false, Validators.required],
    replyFrom: ['NONE'],
  });

ngOnInit(): void {

// this.newMessageForm.controls['title'].setValue('test title'); -> this works, it populates control with the string

this.newsletterToEdit$.pipe(
      tap((newsletter) => {
        console.log('newsletter to edit: ', newsletter);

        // this.newMessageForm.patchValue(newsletter) -> another try
        this.form.setValue({
          title: newsletter.title,
          allowReplies: null,
          groups: newsletter.sentToGroupCode[0],
          message: newsletter.message,
          replyFrom: 'NONE',
          searchedGroups: '1',
          searchedUsers: '2',
          subtitle: newsletter.subtitle,
          users: '3',
        });
      })
    );
}
}

I have confirmed that there is data in the store, but for some reason, the console log is never showing up which indicates that pipe(tap()) are not being called

Answer №1

The main explanation is that ngrx selectors offer cold observables. Cold observables do not generate any data until a subscriber engages with it.

Give this code snippet a try:

this.newsletterToEdit$.subscribe(
 (newsletter) => {
        console.log('newsletter to edit: ', newsletter);

        // this.newMessageForm.patchValue(newsletter) -> another try
        this.form.setValue({
          title: newsletter.title,
          allowReplies: null,
          groups: newsletter.sentToGroupCode[0],
          message: newsletter.message,
          replyFrom: 'NONE',
          searchedGroups: '1',
          searchedUsers: '2',
          subtitle: newsletter.subtitle,
          users: '3',
        });
      })
});

to retrieve a value from it.

Please keep in mind that you should either unsubscribe from it or take a declarative approach (e.g. defining the form as an observable and using async pipe to subscribe to it).

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

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

My custom styles no longer seem to be applying after upgrading Angular Material from version 14 to 15. What could be causing this issue

Having some challenges with the migration from Angular 14 to Angular 15 when it comes to overriding material UI elements and themes. Looking for blog posts or documentation that can provide guidance on how to smoothly transition. Specifically, experiencin ...

What is the method for obtaining the size of the filtered array in Angular 4?

I am currently working with an array of objects that I need to filter based on a search value. component ts filterArray = [ {'id': 1, 'name': 'ABC', 'type': 'IT'}, {'id': 2, 'name&a ...

Having trouble with downloading a zipped folder on the client side in an Angular and Node.js (MEAN) application

I am facing an issue with allowing users to download compressed folders from the server. I have successfully compressed the folder, however, when attempting to read the tar file and send it for download on the client side, the file is either corrupted or o ...

Remove Tr from Repeated *ngFor Using Template-Driven in Angular 2/4

Is it possible to remove a row using template driven form even when arrays are iterated in *ngFor directive? How should I go about this situation? Below is the implementation I have tried. HTML <tr *ngFor="let innerItem of project.material_projec ...

Is there a way to access a file from an S3 bucket URL using Angular?

Currently, I have the URL but I'm not interested in putting in the effort to retrieve the file data or blob. This is my current approach: const url = 'https://s3-us-west-1.amazonaws.com/....'; const a: any = document.createElement('a& ...

Exploring the NextPage type in Next.js

Could someone provide an explanation of the NextPage type within a Next.js TypeScript project? Most sources mention that it is used for type assignment in Next.js, but I am curious about its practical purpose. When and why should we utilize this type? Wha ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

How to exit a dialog in an Angular TypeScript component with precision

Hey there, I'm attempting to close a dialog from the component by specifying the path in .angular-cli.json and calling the function. However, it seems that despite my efforts, the dialog isn't closing and the redirection isn't happening. He ...

How do I properly utilize ngIf in Angular2 to display text exclusively when there is no data retrieved from the server?

After retrieving data from the server using ngFor to display it as a search feature, I want to show a message saying 'There's no result' when there are no search results. How can I achieve this? I have attempted the following approach, but ...

Discover the solution for resolving the issue of HttpErrorResponse 405 not permissible

I am currently managing a website on a VPS that relies on Flask as the backend API server, Angular for the frontend, and Nginx as a reverse proxy. The Nginx has SSL installed, but I am encountering an issue where I can only connect to the Flask server usin ...

Error message from Angular development server: Channel is reporting an error in handling the response. The UNK/SW_UNREACHABLE options

After recently installing a new Angular app, I encountered an issue while running 'ng serve'. The application initially loads without any problems, but after a few seconds, I started seeing a strange error in the console. Channel: Error in handle ...

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

Utilizing external applications within Angular applications

I have the task of creating a user interface for clocker, a CLI-based issue time tracker. Clocker functions as a stand-alone node.js application without any programming interface. To begin tracking time for an issue labeled 123, the command would typically ...

After the initial test is executed, Jasmine's spy-on function proceeds to call the actual function

The issue arises when the second test fails due to an error message stating that "Cannot read property 'get' of undefined". This error occurs because the second test references the real service, which contains a private property called "http" tha ...

Is it possible for me to exclude generic parameters when they can be inferred from another source?

Imagine having a scenario like this: type RecordsObject<T, K extends keyof T> = { primaryKey: K; data: Array<T>; } where the type K is always derived from the type T. Oftentimes, when I try to declare something as of type RecordsObject, ...

Display JSON information in a tabular format

I am trying to populate a table with data from an API response, but I am facing issues printing the data. Specifically, I need to match the "IdLangage" value with the correct cell in the table and display the corresponding translation. The JSON data format ...