Displaying data from an Angular subscription in a user interface form

I am attempting to transfer these item details to a form, but I keep encountering undefined values for this.itemDetails.item1Qty, etc. My goal is to display them in the Form UI.

this.wareHouseGroup = this.formBuilder.group({
  id: this.formBuilder.control(this.warehouse.id),

  sideId: this.formBuilder.control(this.warehouse.sideId.toString(), [
    Validators.required,
    Validators.min(1)
  ]),
  itemDetail: this.formBuilder.group({
    Item1Qty: this.formBuilder.control(this.itemDetails.item1Qty),
    item2Qty: this.formBuilder.control(this.itemDetails.item2Qty),
    item3Qty: this.formBuilder.control(this.itemDetails.item3Qty)
  })
});
this.itemService.getItemDetails(this.item.uid).subscribe((result) => {
      this.itemDetails = result != null ? result : null;

      console.log(this.itemDetails);
    });

here is the console log
{"id":117,"TypeId":1,"item1Qty":563,"item2Qty":3.00,"item3Qty":0,"itemType":"Discount"}
 

Answer №1

It's not possible to assign the itemDetails value directly when initializing/building the form because the itemDetails data is only available during the subscription.

itemDetail: this.formBuilder.group({
    Item1Qty: this.formBuilder.control(this.itemDetails.item1Qty),
    item2Qty: this.formBuilder.control(this.itemDetails.item2Qty),
    item3Qty: this.formBuilder.control(this.itemDetails.item3Qty)
})

Solution

Instead, you can follow these steps:

(1): Do not initialize itemDetails when building the form

itemDetail: this.formBuilder.group({
    Item1Qty: this.formBuilder.control(''),
    item2Qty: this.formBuilder.control(''),
    item3Qty: this.formBuilder.control('')
})

(2) When the subscription event occurs, update the form with the value using patchValue.

this.itemService.getItemDetails(this.item.uid).subscribe(result => {
    this.itemDetails = result != null ? result : null;

    if (!result) return;

    this.wareHouseGroup.controls['itemDetail'].patchValue({
      Item1Qty: this.itemDetails.item1Qty,
      item2Qty: this.itemDetails.item2Qty,
      item3Qty: this.itemDetails.item3Qty
    });

    console.log(this.itemDetails);
});

View Sample Solution on StackBlitz


References

Learn more about updating parts of the data model here

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

Exploring the method to find all corresponding keys within deeply nested objects

Within my 'const', I have an array filled with objects. Each object contains a key called 'image' which holds the value for 'url' as illustrated below. const images =[ { "image": { "url& ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Encountering a ReactJs and TypeScript error: "menuItems.map is not a function, issue with map method"

Greetings! I am currently working on implementing the logic of using useState and mapping an array to show only one dropdown item at a time. Below is my array structure with tags (menu name, links (to router), icon (menu icon), and if there are dropdown i ...

Is there a way to toggle or collapse a table row with a unique identifier using Angular and Bootstrap?

Currently handling Angular and Bootstrap in my work, but facing challenges with table manipulation and collapsing rows. I fetch data from a database and showcase it in a dynamically generated table using *ngFor and two rows within an ng-container. My goal ...

Dynamically load a custom element with a Component

I am attempting to dynamically inject a component into a container. Component: @Component({...}) export class InvestmentProcess{ @ViewChild('container') container; constructor(public dcl: DynamicComponentLoader) {} loadComponent(fo ...

Facebook is failing to detect meta tags for Angular Universal

I am facing an issue where the meta tags are not showing up on my article pages for Facebook sharing, despite using Angular Universal with Server-side rendering. Although Google Indexing is working fine and the meta tags are visible in the page source, the ...

When using Angular and opening a portal in a separate window, what is the best way to connect an overlayRef in order for it to utilize the component's unique styles?

Within the realm of Angular, there exists the CDK Portal library. I came across a scenario online where someone successfully opened a portal in a separate window. Intrigued by this concept, I attempted to create a dialog that would appear in front of a por ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

The type mismatch issue occurs when using keyof with Typescript generics

One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey) and the corresponding value of that key (value): interface ValueHolder<T, H extends keyof T> { modelKey: H; value: T[H]; } My objectiv ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

Using MUI-X autocomplete with TextField disables the ability to edit cells

When I double-click on a cell, everything works fine. However, after the second click to start editing the textfield, the cell stops editing. I can still choose an option though, so I believe the issue lies somewhere in the textField component, possibly i ...

What steps can I take to ensure my CSS selector for the element is functioning properly?

Here is an example of some code: <html> <head> <style> .test{ background-color: red; p { background-color: yellow; } } </style> </head> <body> <div class="test"> ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Guide on transferring individual key values from an array to another array sequentially by clicking a button in Angular/JavaScript

I have an array of objects called marrayval. From this array, I want to extract the 'country' values one by one and push them into the arrayval after each click event. For example, on the first click, I would push C1, on the second click C1, C2, ...

The http post request is functioning properly in postman, but it is not working within the ionic app

I am currently developing an app in ionic v3 within visual studio (Tools for Apache Cordova). On one of the screens in my app, I gather user information and send it to an API. However, I'm encountering an issue with the HTTP POST request that I'm ...

Alternatives to using wildcards in TypeScript

In my code, I have defined an interface called ColumnDef which consists of two methods: getValue that returns type C and getComponent which takes an input argument of type C. Everything is functioning properly as intended. interface ColumnDef<R, C> { ...

Angular8 is displeased with the unexpected appearance of only one argument when it was clearly expecting two

Even though I have declared all my requirements statically in my component.html file, why am I receiving an error stating "Expected 2 arguments but got 1"? I use static concepts, so it's confusing to encounter this type of error. Below you can see th ...

Converting JSON to a specialized object in Python

Currently grappling with a challenging problem that has left me stumped. I am attempting to extract and convert objects from JSON files into specific Python objects. For instance, I have JSON data structured like this: { "Class1":{ &q ...

Angular HttpClient Catch Return Value

In my quest to develop a universal service for retrieving settings from the server, I've encountered an issue. When errors arise, I want to intercept them and provide a default value (I have a predetermined configuration that should be utilized when e ...