The form doesn't seem to be functioning properly when I incorporate the formgroup and service within the ngOnInit() method

I implemented the formgroup code in ngOnInit() and also utilized a service in ngOnInit(). However, the asynchronous nature of the form is causing issues. The full code on StackBlitz works when I use dummy JSON data within the constructor. Check out the working-form-dummyjson CODE URL here.

Although I received a response from the service by using it inside ngOnInit(), the form is not functioning properly due to the asynchronous call. You can view the code with the service implementation that is not working here.

The snippet below shows the service code where I fetch the data: this.dataService.getData().then(data => this.users=data); I attempted to include formgroup code within the service but encountered errors. Please refer to the console screenshot for the response.

https://i.sstatic.net/GK9iK.png

Here's a glimpse of my constructor code:

constructor(private dataService: DataService,private fb: FormBuilder) {
this.myForm = this.fb.group({
users: this.fb.array([])
})
this.users =[{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
this.test =   [{"name":"manu","displayOrder":1,"data":[{"category":"electrical","name":"ele"}]},{"name":"divya","displayOrder":1,"data":[{"category":"tech","name":"ea_tcv"}]}];
}

Next, here's the ngOnInit() code which initializes the service and forms:

ngOnInit() {
console.log("ramu");
this.dataService.getData().then(data => console.log(data));
this.dataService.getData().then(data => this.users=data);
this.dataService.getData().then(data => this.test=data);

let dataArr = new FormArray([]);
dataArr.push(new FormGroup({
'name': new FormControl(this.users[0].data[0].name),
'category': new FormControl(this.users[0].data[0].category)
}));

let formArr = <FormArray>this.myForm.controls.users;
formArr.push(this.fb.group({
name: this.users[0].name,
displayOrder: this.users[0].displayOrder,
data: dataArr
}));
}

Answer №1

To ensure that the values are indeed available before populating your form, simply call a method or populate your form within the callback function then:

this.dataService.getData().then(data => {this.users = data; this.patch()});

The method looks like this:

patch() {
  let dataArr = new FormArray([]);
  dataArr.push(new FormGroup({
    'name': new FormControl(this.users[0].data[0].name),
    'category': new FormControl(this.users[0].data[0].category)
  }));

  let formArr = <FormArray>this.myForm.controls.users;
    formArr.push(this.fb.group({
    name: this.users[0].name,
    displayOrder: this.users[0].displayOrder,
    data: dataArr
  }));
}

You can view your modified code on StackBlitz

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

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Is there a way to selectively filter and display certain data in an Angular data table?

https://i.sstatic.net/0N3OZ.jpg I am currently working on a project using Angular 7 frameworks that involves dealing with large amounts of data. One of the tasks is to filter out trial units based on the 'userName' field in the raw data. I have ...

App routing functions correctly when navigating within the app, but does not work when directly entering a URL into

After creating an angular 11 app with routing modules, I encountered an issue where typing a specific path in the browser address bar did not navigate to the expected destination. The app functioned correctly when started from the domain URL, leading to th ...

Angular - dynamically adjust overlay margins based on positioning strategy

Currently, I am in the process of developing a custom overlay component that requires setting a margin of 0.5rem. The margin needs to be dynamic based on the position of the overlay, such as when originY === 'bottom' => margin-top: 0.5rem, amo ...

Creating a HTTP Post request in Angular with DocRaptor to receive the download URL in the response

Struggling to integrate Angular5 with DocRaptor has led me to hit a roadblock. Surprisingly, the DocRaptor website lacks any documentation on how to combine it with Angular, only offering a beginner's guide for 'other'. I've scoured thr ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

Child routes cannot be included when ..., so make sure to specify "..." in the parent route path

I've been working on setting up child routing within my project, and here is the current folder structure I have: app |--home/ | |--home.component.ts |--login/ | |--login.ts |--appShell/ | |--app.component.ts |--apps/ |- ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

The challenge of generics in Typescript: destructuring and spreading

I am facing an issue with destructing parameters and creating a new object of the same type in Typescript. The following code functions properly: function customFunc<T extends { attribute: string }>(parameter: T): T { const { ...rest } = paramete ...

The structure of '({ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Rec...' does not match the expected type 'Route[]'

I encountered an error while setting up my application's routes. The error message reads: "Type '({ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Rec...' is not assignable to type 'Route[] ...

Numerous documents for route definitions

Typically, I usually have all my route definitions in a single file, such as app.routing.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@a ...

Troubleshooting the Angular 7 mat-select issue caused by the "ellipsis" CSS property with three dots

I am facing an issue with a mat-select property called "ellipsis". The three points appear in a different color than the text itself. I attempted to change it to white using the following code, but the dots still remain black. ::ngdeep .example{ ...

Issue customizing static method of a subclass from base class

Let me illustrate a simplified example of my current code: enum Type {A, B} class Base<T extends Type> { constructor(public type: T) {} static create<T extends Type>(type: T): Base<T> { return new Base(type); } } class A exte ...

When using Angular 2 formControl, manually changing the value may not be detected by the form

Having a simple form (as shown below), I am encountering an issue: Manually entering input value causes form.controls['myValue'].value to change If #myInput value is changed programmatically, the form completely ignores that change What could ...

What is the best way to transform a string array into a number array?

I'm attempting to convert a string array into a number array and after conducting some research online, I came across this solution: let numbersAsStringArray = originalQueryParams[property] ?? [] let numbers = numbersAsStringArray.map((i) => ...

Combining the values of a particular key with duplicate objects into a single object within an array of JSON objects using Angular and Typescript

I'm currently facing a challenge in my Angular project where I have an array of JSON objects. These objects are very similar, differing only in one key-value pair. My goal is to combine these similar objects into one while appending the varying values ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Handling click events on Datatable.net paging buttons

My goal is to capture the click event when one of the paging buttons on the Datatable is clicked in Angular. I'm not exactly sure how to go about accomplishing this! If I refer to this example, how can I adapt the code for Angular? Specifically, how ...