How can you establish the default value for a form from an Observable?

Check out my TypeScript component below

export interface Product{
    id?:string,
    name:string,
    price:string;
    quantity:string;
    tags:Tags[];
    description:string;
    files: File[];
}

product$:Observable<Product | undefined>;

ngOnInit(): void { 
  this.store.dispatch(new productActions.LoadProduct(fromProduct.getCurrentProductId.toString()));
  this.product$ = this.store.pipe(select(fromProduct.getCurrentProduct));
}

The last two statements retrieve the value of the product observable and function properly.

this.product = this.fb.group({
    name:['',[
      Validators.required,
      Validators.minLength(1),
      Validators.maxLength(128)
    ]],
    price:['',
    Validators.required],
    tags:this.fb.array(this.tags),
    quantity:['',Validators.required],
    description:['',
    Validators.required]
  });
}

My current aim is to set the default Form values from Product$ (observable)

In the above code, the default value for name is set to ''. However, I would like to set a default value from (product$ | async).name----->> This functionality works correctly in HTML, but I am unsure how to implement it in TypeScript.

Thank you for your assistance.

Answer №1

To ensure your FormGroup initialization is executed only once and then unsubscribed, consider placing it within a subscribe function. Remember to include the first operator in order to achieve this.

this.product$
    .pipe(first())
    .subscribe(product => {
        this.product = this.fb.group({
            name:[product.name,[
              Validators.required,
              Validators.minLength(1),
              Validators.maxLength(128)
            ]],
            price:['',
            Validators.required],
            tags:this.fb.array(this.tags),
            quantity:['',Validators.required],
            description:['',
            Validators.required]
          });
        }
    });

Answer №2

To ensure you can access any passed values, it is important to subscribe to the observable. Here's an example of how you can achieve this:

const data$ = this.dataService.getDataObservable();
data$.subscribe(data => {
  // Do something with the received data
});

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

RxJs: Generating an observable based on changes in a field's value

Is there a way to generate an Observable using the variable this.pending as its source? I'm looking to create an Observable that will produce a new feed each time the value of this.pending changes. For example, if I update this.pending to be false i ...

Typescript overloaded function parameters explained

I am currently working on the following code snippet: import React from "react"; interface BaseFormValue { name: string; } export interface NewFormValue extends BaseFormValue { email: string; } export interface ExistingFormValue extends Ba ...

Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

How can Angular send datetime data to Nodejs in the most effective manner?

Working with the primeng calendar component within a template-driven form, I encountered an issue. When passing the date 16/05/2018 11:45 from Angular to Node, it gets converted to 2018-05-16T06:15:33.000Z. I discovered that I could convert it back to IST ...

Using numerous maps within Ionic applications with the JavaScript SDK

Currently, I am utilizing the Google Maps (Javascript SDK) in Ionic V3 and have successfully created two pages with map views. Interestingly, while the first page displays the map correctly, upon opening the second page, the map shows up with grey lines, ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Is there a way to access URL parameters using a router in Angular 7?

I am facing a challenge with the Angular 7 router in understanding how to utilize the "token" get parameter from different parts of the URL. Below is the code snippet where I have defined multiple routes: const myRoutes: Routes = [ { path: 'register ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

Ways to bypass certificate verification

Every time I make a request from the server to fetch data, I encounter a certificate error. GET https://ip:5001/api/cards/online net::ERR_CERT_COMMON_NAME_INVALID To resolve this issue, I made the decision to bypass certificate verification. Can you provi ...

The 'setComputed' property is not mandatory in the type definition, however, it is a necessary component in the 'EntityExample' type

I'm encountering an issue while trying to create a factory for updating an entity. The error I'm facing is related to the usage of afterload: Entity: import { Entity, PrimaryGeneratedColumn, Column, OneToMany, BaseEntity, AfterLoad, ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

"Utilizing an if-else statement within a forEach loop

I have an array of ages and I want to determine the age range for each age along with the count, then push it into my object. The issue I am facing is that if there are multiple ages in the same range, it gets pushed twice. I only want to push it once and ...

A guide to successfully deploying Angular 4 applications on app engine without the hassle of uploading a hefty 220MB of node_modules

Is it possible to deploy my Angular 4 apps on Google Cloud App Engine while only uploading the dist folder? I currently have 220mb of data in node_modules, but I only want to deploy the dist folder which is around 10mb after running ng build --prod. In t ...

How can I remove specific items from a PrimeNG PickList?

Currently, I'm working on a page where updates are made using PrimeNG PickList. The initial state of the target list is not empty, but when selected items are moved from source to target list, they are not removed from the source list as expected. Fr ...

Encountered an issue while resolving symbol values statically within my exclusive set of modules

Encountered an error while resolving symbol values statically. The function 'DataModule' is not supported. Consider using a reference to an exported function instead of a function or lambda, resolving the symbol DataModuleRoot in E:/shopify-clien ...

Locating a class variable using a string chosen from a DropDown menu

In my Tv class, I have several string variables. One requirement is for the user to select an option from a DropDown list and input a value. This entered value should then be stored in the Tv class under a variable with a similar name to the selected optio ...